Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

interface - 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.

  1. Do I implement Comparable with the class I'm sorting, or do I create a new class?
  2. How do I instantiate the SortedMap and pass in the Comparator?
  3. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. The simpler way is to implement Comparable with your existing objects, although you could instead create a Comparator and pass it to the SortedMap.
    Note that Comparable and Comparator are two different things; a class implementing Comparable compares this to another object, while a class implementing Comparator compares two other objects.
  2. If you implement Comparable, you don't need to pass anything special into the constructor. Just call new TreeMap<MyObject>(). (Edit: Except that of course Maps need two generic parameters, not one. Silly me!)
    If you instead create another class implementing Comparator, pass an instance of that class into the constructor.
  3. 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...