Java: SortedMap, TreeMap, Comparable? How to use?

后端 未结 5 748
别跟我提以往
别跟我提以往 2020-12-06 03:16

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.

5条回答
  •  悲&欢浪女
    2020-12-06 03:44

    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() {
        int compare(MyClass o1, MyClass o2) { ... }
    });
    

    3. Yes.

提交回复
热议问题