Java:SortedMap,TreeMap,Comparable?如何使用? [英] Java: SortedMap, TreeMap, Comparable? How to use?
问题描述
我有一个对象列表,我需要根据其中一个字段的属性进行排序。我听说SortedMap和Comparators是最好的方法。
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并传入比较器?
- 排序如何工作?它会在插入新对象时自动对所有内容进行排序吗?
编辑:
此代码为给我一个错误:
This code is giving me an error:
private TreeMap<Ktr> collection = new TreeMap<Ktr>();
(Ktr实现 Comparator< Ktr>
) 。 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
,尽管你可以改为创建一个比较器
并将其传递给SortedMap
。
注意可比较
和比较者
是两件不同的事情;实现Comparable
的类将此
与另一个对象进行比较,而实现Comparator的类
比较两个其他对象。 - 如果您实施
Comparable
,则不需要将任何特殊内容传递给构造函数。只需调用新的TreeMap< MyObject>()
。 (编辑:除了当然地图
需要两个通用参数,而不是一个。傻我!)
如果您改为创建另一个实现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
一样,您可以改为创建比较器< MyObject>
并将其传递给 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屋!