实现 Map 并保持插入顺序的 Java 类? [英] Java Class that implements Map and keeps insertion order?
问题描述
我正在寻找具有键值关联但不使用哈希的 Java 类.这是我目前正在做的事情:
I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing:
- 将值添加到
Hashtable
. - 获取
Hashtable.entrySet()
的迭代器. - 遍历所有值并:
- Add values to a
Hashtable
. - Get an iterator for the
Hashtable.entrySet()
. - Iterate through all values and:
- 为迭代器获取
Map.Entry
. - 根据值创建一个
Module
类型的对象(自定义类). - 将类添加到 JPanel.
- Get a
Map.Entry
for the iterator. - Create an object of type
Module
(a custom class) based on the value. - Add the class to a JPanel.
这样做的问题是我无法控制取回值的顺序,因此我无法按给定顺序显示值(没有对顺序进行硬编码).
The problem with this is that I do not have control over the order that I get the values back, so I cannot display the values in the a given order (without hard-coding the order).
我会为此使用 ArrayList
或 Vector
,但稍后在代码中我需要获取给定 Key 的 Module
对象,我不能用 ArrayList
或 Vector
.
I would use an ArrayList
or Vector
for this, but later in the code I need to grab the Module
object for a given Key, which I can't do with an ArrayList
or Vector
.
有谁知道有一个免费/开源的 Java 类可以做到这一点,或者知道一种根据添加时间从 Hashtable
中获取值的方法吗?
Does anyone know of a free/open-source Java class that will do this, or a way to get values out of a Hashtable
based on when they were added?
谢谢!
推荐答案
我建议使用 LinkedHashMap
或 TreeMap
.LinkedHashMap
保持键的插入顺序,而 TreeMap
通过 Comparator
或自然的 Comparable<保持排序/code> 元素的顺序.
I suggest a LinkedHashMap
or a TreeMap
. A LinkedHashMap
keeps the keys in the order they were inserted, while a TreeMap
is kept sorted via a Comparator
or the natural Comparable
ordering of the elements.
由于不必保持元素排序,LinkedHashMap
在大多数情况下应该更快;TreeMap
对于 containsKey
、get
、put
具有 O(log n)
性能,和 remove
,根据 Javadocs,而 LinkedHashMap
是 O(1)
每个.
Since it doesn't have to keep the elements sorted, LinkedHashMap
should be faster for most cases; TreeMap
has O(log n)
performance for containsKey
, get
, put
, and remove
, according to the Javadocs, while LinkedHashMap
is O(1)
for each.
如果您的 API 只需要可预测的排序顺序,而不是特定的排序顺序,请考虑使用这两个类实现的接口,NavigableMap
或 SortedMap
.这将允许您不会将特定实现泄漏到您的 API 中,并在之后随意切换到这些特定类或完全不同的实现.
If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap
or SortedMap
. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.
这篇关于实现 Map 并保持插入顺序的 Java 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!