开发者

Custom String Length Comparator: what's my mistake?

开发者 https://www.devze.com 2023-03-03 12:45 出处:网络
I defined a custom comparator to sort the name(String) variable of my objects by length. Here\'s the code from my person class:

I defined a custom comparator to sort the name(String) variable of my objects by length.

Here's the code from my person class:

class MyNameLengthCompare implements Comparator<Person> {

        @Override
        public int compare(Person a, Person开发者_如何学运维 b) {
            if(a.getName().length() > b.getName().length()) {
                return -1;
            } else if (a.getName().length() < b.getName().length()) {
                return 1;
            } else
                return 0;
        }

    }

Then in my main method I called Collections.sort(personList, new MyNameLengthCompare); and then I added it to my TreeSet myTreeSet.addAll(personList)

But its not sorting by length of name :(


You don't need to sort it before you add it to the tree set. The only thing that matters is whether or not the tree set has the comparator.


Do you construct the TreeSet with the Comparator? If not, the Tree likely ignores your comparator and previous sorting and uses the natural sorting of its contents, that specified by its Comparable compareTo method.


Well, I think there is the next issue :

1) Collections.sort are sorting correctly your list.

2) When you add this collection to the TreeSet, it is sorted one more time, and at this time is used Person.compareTo();

3) Try to not use Comparator, try to implement Comparable interface in the Person class and add list to the tree directly, without sorting with Collections.

0

精彩评论

暂无评论...
验证码 换一张
取 消