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

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

问题描述

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

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并传入比较器?

  3. 排序如何工作?它会在插入新对象时自动对所有内容进行排序吗?

编辑:
此代码为给我一个错误:

This code is giving me an error:

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

(Ktr实现 Comparator< Ktr> ) 。 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 ,尽管你可以改为创建一个比较器并将其传递给 SortedMap

    注意 可比较 比较者 是两件不同的事情;实现 Comparable 的类将与另一个对象进行比较,而实现 Comparator的类比较两个其他对象。

  2. 如果您实施 Comparable ,则不需要将任何特殊内容传递给构造函数。只需调用新的TreeMap< MyObject>()。 (编辑:除了当然地图需要两个通用参数,而不是一个。傻我!)

    如果您改为创建另一个实现 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 一样,您可以改为创建比较器< MyObject> 并将其传递给 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天全站免登陆