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.
Comparablewith your existing objects, although you could instead create aComparatorand pass it to theSortedMap.Note that
ComparableandComparatorare two different things; a class implementingComparablecomparesthisto another object, while a class implementingComparatorcompares two other objects.Comparable, you don’t need to pass anything special into the constructor. Just callnew TreeMap<MyObject>(). (Edit: Except that of courseMapsneed two generic parameters, not one. Silly me!)If you instead create another class implementing
Comparator, pass an instance of that class into the constructor.TreeMapJavadocs.Edit: On re-reading the question, none of this makes sense. If you already have a list, the sensible thing to do is implement
Comparableand then callCollections.sorton it. No maps are necessary.A little code:
As with the
SortedMap, you could instead create aComparator<MyObject>and pass it toCollections.sort(List, Comparator).