Java: SortedMap, TreeMap, Comparable? How to use?
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.
- Do I implement Comparable with the class I'm sorting, or do I create a new class?
- How do I instantiate the SortedMap and pass in the Comparator?
- How does the sorting work? Will it automatically sort everything as new objects are inserted?
EDIT: This code is giving me an error:
private TreeMap<Ktr> collection = new TreeMap<Ktr>();
(Ktr implements Comparator<Ktr>
). Eclipse says it is expecting something like TreeMap<K, V>
, so the number of parameters I'm supplying is incorrect.
Solution 1:
- 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>()
. (Edit: 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.
Edit: 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.
A little code:
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);
As with the SortedMap
, you could instead create a Comparator<MyObject>
and pass it to Collections.sort(List, Comparator)
.
Solution 2:
1.
That depends on the situation. Let's say the object A should sort before the object B in your set. If it generally makes sense to consider A less than B, then implementing Comparable would make sense. If the order only makes sense in the context in which you use the set, then you should probably create a Comparator.
2.
new TreeMap(new MyComparator());
Or without creating a MyComparator class:
new TreeMap(new Comparator<MyClass>() {
int compare(MyClass o1, MyClass o2) { ... }
});
3. Yes.