自定义字符串长度比较器:我的错误是什么?
我定义了一个自定义比较器来按长度对对象的名称(字符串)变量进行排序。
这是我的 person 类中的代码:
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;
}
}
然后在我的 main 方法中,我调用了 Collections.sort(personList, new MyNameLengthCompare);
,然后将其添加到我的 TreeSet myTreeSet.addAll(personList)< /code>
但它不按名称长度排序:(
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 :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在将其添加到树集中之前,不需要对其进行排序。唯一重要的是树集是否有比较器。
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.
你用Comparator构建TreeSet吗?如果不是,树可能会忽略您的比较器和先前的排序,并使用其内容的自然排序,这是由其 ComparablecompareTo 方法指定的。
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.
好吧,我认为还有下一个问题:
1)Collections.sort 正在正确排序您的列表。
2)当你把这个集合添加到TreeSet中时,它又被排序了一次,此时使用的是Person.compareTo();
3)尽量不使用Comparator,尝试在Person类中实现Comparable接口,直接将list添加到树中,而不用Collections排序。
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.