【问题标题】:From Sorting Arrays of Objects to ArrayList<Object>从排序对象数组到 ArrayList<Object>
【发布时间】:2013-04-07 00:37:03
【问题描述】:

我有这个:

Comparator<Item> ignoreLeadingThe = new Comparator<Item>() {
                public int compare(Item a, Item b) {
                    String newA = a.name.replaceAll("(?i)^the\\s+", "");
                    String newB = b.name.replaceAll("(?i)^the\\s+", "");
                    return newA.compareToIgnoreCase(newB);
                }
            };

Array.sort(MyItemArrayOfObjects, ignoreLeadingThe);

我停止使用数组,现在使用 ArrayList。所以当我这样做时:

Collections.sort(MyItemArrayListOfObjects, ignoreLeadingThe);

我什至无法弄清楚它现在排序的模式。我可以像这样做一个干净的开关吗? (完全有可能我用上面没有提到的东西打破了这个,如果这是正确的,那么这就是我需要知道的全部)

注意:最初,对于数组,我只是尝试按字母顺序排列列表并忽略开头的“The”。它适用于 Android 应用程序。每个列表行项目数据都包装在我传递给 ArrayAdapter 的对象中。我只是想在该对象中获取一个 ArrayList 并将其按字母顺序排列。所以本质上,它是一个 ArrayList,里面有几个 ArrayList。

【问题讨论】:

  • 一般来说,是的,您可以将数组上的 Array.sort 替换为数组包含的相同对象的 ArrayList 上的 Collections.sort。但是,您还没有显示所有代码,并且您的描述有点神秘。所以,请展示一个我们可以实际编译和运行的小而完整的代码示例。
  • 只要您使用相同的比较器,结果应该是相同的。看到这个Ideone
  • @Perception 谢谢。这就是我需要知道的。努力

标签: java android arrays arraylist


【解决方案1】:

您的比较器看起来不错

坏消息是它不会缓存结果字符串。所以你的排序会创建o(N*log(N))Pattern's、Matcher's 和 String's 对象,而不是谈论其中一些对象的创建速度不是很快。

UPD

建议在为接口实现的方法上使用@Override,并在子类中覆盖。

【讨论】:

    【解决方案2】:

    它对 Collections.sort 非常有效,我只建议改进 Comparator

        Comparator<Item> ignoreLeadingThe = new Comparator<Item>() {
            Pattern pattern = Pattern.compile("(?i)^the\\s+");
            public int compare(Item a, Item b) {
                String newA = pattern.matcher(a.name).replaceAll("");
                String newB = pattern.matcher(b.name).replaceAll("");
                return newA.compareToIgnoreCase(newB);
            }
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2021-03-16
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多