排序使用Collections.sort自定义类数组列表字符串自定义、数组、字符串、列表

2023-09-05 10:13:57 作者:我与君偕老

我试图通过宣称自己的匿名比较我的自定义类使用Collections.sort数组列表进行排序。但排序不按预期工作。

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.

我的code是

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.

推荐答案

像亚当说,简单地做:

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

该方法String.compareTo进行逐一比较,你的原来的code被否定。例如字符串数字1 number123 时相比会产生-2和2分别。

The method String.compareTo performs a lexicographical comparison which your original code is negating. For example the strings number1 and number123 when compared would produce -2 and 2 respectively.

通过简单地返回1,0或-1有一个机会(因为正在发生的事情对你而言)合并的合并部分来挑选 Col​​lections.sort 方法无法列表中的产生是不按字母顺序排列的列表的字符串之间充分区分。

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.sort method is unable to differentiate sufficiently between the strings in the list resulting in a list that isn't alphabetically sorted.

 
精彩推荐
图片推荐