java 使用 Collections.sort 对自定义类数组列表字符串进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10091110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:34:49  来源:igfitidea点击:

Sorting custom class array-list string using Collections.sort

javaandroidsortingcollectionsarraylist

提问by kaibuki

I am trying to sort my custom class array-list using Collections.sort by declaring my own anonymous comparator. But the sort is not working as expected.

我试图通过声明我自己的匿名比较器来使用 Collections.sort 对我的自定义类数组列表进行排序。但是排序没有按预期工作。

My code is

我的代码是

Collections.sort(arrlstContacts, new Comparator<Contacts>() {

        public int compare(Contacts lhs, Contacts rhs) {

            int result = lhs.Name.compareTo(rhs.Name);

            if(result > 0)
            {
                return 1;

            }
            else if (result < 0)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    });

The result is not in sorted order.

结果没有排序。

回答by Nick Holt

Like Adam says, simply do:

就像亚当说的,简单地做:

Collections.sort(
  arrlstContacts, 
  new Comparator<Contacts>() 
  {
    public int compare(Contacts lhs, Contacts rhs) 
    {
      return lhs.Name.compareTo(rhs.Name);
    }
  }
);

The method String.compareToperforms a lexicographical comparison which your original code is negating. For example the strings number1and number123when compared would produce -2 and 2 respectively.

该方法String.compareTo执行您的原始代码否定的字典顺序比较。例如,字符串number1number123when 比较将分别产生 -2 和 2。

By simply returning 1, 0 or -1 there's a chance (as is happening for you) that the merge part of the merge sort used Collections.sortmethod is unable to differentiate sufficiently between the strings in the list resulting in a list that isn't alphabetically sorted.

通过简单地返回 1、0 或 -1,有可能(正如您正在发生的那样)合并排序所用Collections.sort方法的合并部分无法充分区分列表中的字符串,从而导致列表未按字母顺序排序.

回答by Mark Pazon

As indicated by Adam, you can use return (lhs.Name.compareTo(rhs.Name));likeso:

正如 Adam 所指出的,您可以使用return (lhs.Name.compareTo(rhs.Name));likeso:

Collections.sort(arrlstContacts, new Comparator<Contacts>() {
     public int compare(Contacts lhs, Contacts rhs) {
         return (lhs.Name.compareTo(rhs.Name));
     }
});