问题
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