Java:TreeSet 和 LinkedList 的问题
我有一个未排序的链表。为了对其进行排序,我想将这些值放入带有比较器的 TreeSet 中,然后将这些值作为新的链接列表返回。然而,它失败了。
比较器:
public class SortSpeciesByCommonName implements Comparator<Species> {
/**
* a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
*/
@Override
public int compare(Species arg0, Species arg1) {
return arg0.getName().compareTo(arg1.getName()); //arg.getName() is String
}
}
排序功能:
public static LinkedList<Species> sortedAnimals(LinkedList<Species> animals) {
TreeSet<Species> sortedBreeds = new TreeSet<Species>(new SortSpeciesByCommonName());
sortedBreeds.addAll(animals);
return new LinkedList<Species>(sortedBreeds);
}
测试值时,所有内容似乎仍按插入顺序排列。
I have an unsorted linked list. To sort it, I thought I'd put the values into a TreeSet with a comparator supplied, then return those values as a new linked list. Yet, it fails.
Comparator:
public class SortSpeciesByCommonName implements Comparator<Species> {
/**
* a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
*/
@Override
public int compare(Species arg0, Species arg1) {
return arg0.getName().compareTo(arg1.getName()); //arg.getName() is String
}
}
Sorting function:
public static LinkedList<Species> sortedAnimals(LinkedList<Species> animals) {
TreeSet<Species> sortedBreeds = new TreeSet<Species>(new SortSpeciesByCommonName());
sortedBreeds.addAll(animals);
return new LinkedList<Species>(sortedBreeds);
}
When testing the values, everything appears to still be in insertion order.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不使用 Collections.sort(List,Comparator):
我们无法真正调试您的程序以及列表未排序的原因。你能提供一个测试用例吗?
Species.getName()
的签名是什么?它是一个字符串
吗?Why don't you use Collections.sort(List,Comparator):
We cannot really debug your program and why the list isn't sorted. Can you provide a test case? What's the signature of
Species.getName()
? Is it aString
?这并不能直接回答您的问题,但您可能会发现使用
Collections.sort
传入列表和比较器会更容易。使用TreeSet
保存。This doesn't answer your question directly, but you may find it easier to just use
Collections.sort
, passing in your list and comparator. Saves using aTreeSet
.