1

我知道ArrayList提供在位置获取项目的能力get(position),而LinkedHashTable提供排序,但它无法在位置获取项目。所以,问题:java中的任何通用集合是否具有以下特性:

  • 排序

  • 按位置获取

  • 提供 Key/Value 泛型类型。

请给我列出功能的代码示例,如果需要通用存在。

4

2 回答 2

4

您在寻找TreeMapSortedMap吗?

TreeMap 和 SortedMap 都提供:

  1. 提供关键元素的自然排序。
  2. 是键/值对
  3. 获取基于 Key 的值。

顺便提一句:

LinkedHashMap只是维护一个插入顺序,它没有排序,它只是有一个订单

于 2012-11-23T05:42:32.097 回答
2

我为之前过于复杂的事情道歉!

使用树形图。当你想

get(position)

只需执行以下操作:

K key = treemap.getKeys().get(position)
V value = treemap.get(key);

===========================

我以前的旧的过于复杂的错误答案:

您可以使用ArrayList<Pair<K implements Comparable,V>>您在Pair<K,V>K 上实现了 Comparable 的地方。然后你可以Collections.sort(List<Pair<K,V>)在 Arraylist 上使用。

然后您将维护 aHashMap<K,V>以便您可以按 K 检索元素。这意味着您必须记住更新两个数据结构。这意味着 O(N) 添加一个元素 :( 。此外,为了简化逻辑,您可以将 HashMap 和 ArrayList 包装在一个对象中。

public class Pair<K extends  Comparable<K>, V> implements Comparable {

    private final K first;

    private final V second;

    public Pair(K first, V second) {
        this.first = first;
        this.second = second;
    }

    public K getFirst() {
        return first;
    }

    public V getSecond() {
        return second;
    }

    public int compareTo(K other) ; // TODO
}
于 2012-11-23T05:56:06.913 回答