Java:SortedMap、TreeMap、Comparable?如何使用? [英] Java: SortedMap, TreeMap, Comparable? How to use?
问题描述
我有一个对象列表,我需要根据其中一个字段的属性进行排序.我听说 SortedMap 和 Comparator 是最好的方法.
I have a list of objects I need to sort according to properties of one of their fields. I've heard that SortedMap and Comparators are the best way to do this.
- 我是对正在排序的类实施 Comparable 还是创建一个新类?
- 如何实例化 SortedMap 并传入 Comparator?
- 排序是如何工作的?是否会在插入新对象时自动对所有内容进行排序?
这段代码给了我一个错误:
This code is giving me an error:
private TreeMap<Ktr> collection = new TreeMap<Ktr>();
(Ktr 实现了 Comparator
).Eclipse 说它期待像 TreeMap<K, V>
这样的东西,所以我提供的参数数量不正确.
(Ktr implements Comparator<Ktr>
). Eclipse says it is expecting something like TreeMap<K, V>
, so the number of parameters I'm supplying is incorrect.
推荐答案
- 更简单的方法是使用现有对象实现
Comparable
,尽管您可以改为创建一个Comparator
并将其传递给SortedMap
.
请注意,Comparable
和Comparator
是两种不同的东西;实现Comparable
的类将this
与另一个对象进行比较,而实现Comparator
的类将两个other 对象进行比较.莉> - 如果你实现了
Comparable
,你就不需要向构造函数传递任何特殊的东西.只需调用new TreeMap
.(当然,() Maps
需要两个通用参数,而不是一个.傻我!)
如果您改为创建另一个实现Comparator
的类,请将该类的实例传递给构造函数. - 是的,根据
TreeMap
Javadocs.
- The simpler way is to implement
Comparable
with your existing objects, although you could instead create aComparator
and pass it to theSortedMap
.
Note thatComparable
andComparator
are two different things; a class implementingComparable
comparesthis
to another object, while a class implementingComparator
compares two other objects. - If you implement
Comparable
, you don't need to pass anything special into the constructor. Just callnew TreeMap<MyObject>()
. ( Except that of courseMaps
need two generic parameters, not one. Silly me!)
If you instead create another class implementingComparator
, pass an instance of that class into the constructor. - Yes, according to the
TreeMap
Javadocs.
<小时>
在重新阅读问题时,这些都没有意义.如果你已经有了一个列表,明智的做法是实现 Comparable
然后调用 Collections.sort
就可以了.不需要地图.
On re-reading the question, none of this makes sense. If you already have a list, the sensible thing to do is implement Comparable
and then call Collections.sort
on it. No maps are necessary.
一点代码:
public class MyObject implements Comparable<MyObject> {
// ... your existing code here ...
@Override
public int compareTo(MyObject other) {
// do smart things here
}
}
// Elsewhere:
List<MyObject> list = ...;
Collections.sort(list);
与 SortedMap
一样,您可以改为创建一个 Comparator
并将其传递给 Collections.sort(List, Comparator)
.
As with the SortedMap
, you could instead create a Comparator<MyObject>
and pass it to Collections.sort(List, Comparator)
.
这篇关于Java:SortedMap、TreeMap、Comparable?如何使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!