Java – use collections.sort to sort the list strings of custom class arrays

I tried to sort my list of custom class arrays using collections. Sort by declaring my own anonymous comparator. But this didn't work as expected

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 results are not in the sort order

resolvent:

As Adam said, just:

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

The method string.compareto performs dictionary comparison, and its original code is negative. For example, the strings Number1 and number123 during comparison will produce - 2 and 2, respectively

By simply returning 1,0 or - 1, it is possible (as you have happened) that the merged part of the merge sort using the collections.sort method cannot be fully distinguished between the strings in the list, resulting in the list not being 'sorted alphabetically

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>