Java:SortedMap、TreeMap、Comparable?如何使用? [英] Java: SortedMap, TreeMap, Comparable? How to use?

查看:26
本文介绍了Java:SortedMap、TreeMap、Comparable?如何使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,我需要根据其中一个字段的属性进行排序.我听说 SortedMap 和 Comparator 是最好的方法.

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. 我是对正在排序的类实施 Comparable 还是创建一个新类?
  2. 如何实例化 SortedMap 并传入 Comparator?
  3. 排序是如何工作的?是否会在插入新对象时自动对所有内容进行排序?

这段代码给了我一个错误:

This code is giving me an error:

private TreeMap<Ktr> collection = new TreeMap<Ktr>();

(Ktr 实现了 Comparator).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.

推荐答案

  1. 更简单的方法是使用现有对象实现 Comparable,尽管您可以改为创建一个 Comparator 并将其传递给 SortedMap.
    请注意,ComparableComparator 是两种不同的东西;实现Comparable 的类将this 与另一个对象进行比较,而实现Comparator 的类将两个other 对象进行比较.莉>
  2. 如果你实现了Comparable,你就不需要向构造函数传递任何特殊的东西.只需调用 new TreeMap().(当然,Maps 需要两个通用参数,而不是一个.傻我!)
    如果您改为创建另一个实现 Comparator 的类,请将该类的实例传递给构造函数.
  3. 是的,根据 TreeMap Javadocs.
  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>(). ( 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.

<小时>

在重新阅读问题时,这些都没有意义.如果你已经有了一个列表,明智的做法是实现 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 一样,您可以改为创建一个 Comparator 并将其传递给 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆