Sorting custom class array-list string using Collections.sort

前端 未结 2 1167
不思量自难忘°
不思量自难忘° 2021-02-06 17:47

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.

My code is

相关标签:
2条回答
  • 2021-02-06 18:26

    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.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.

    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.

    0 讨论(0)
  • 2021-02-06 18:35

    As indicated by Adam, you can use 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));
         }
    });
    
    0 讨论(0)
提交回复
热议问题