Custom String Length Comparator: what's my mistake?

一世执手 提交于 2019-12-10 22:49:52

问题


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 :(


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5925532/custom-string-length-comparator-whats-my-mistake

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!