Java类实现Map并保持插入顺序? [英] 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
,但后来我需要的代码获取给定密钥的模块
对象,我不能使用 ArrayList
或矢量
。
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 c这样做的懒惰,或者是根据添加时间,从 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
通过比较器
或元素的自然可比较
顺序。
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
具有 O(log n)
表现为 containsKey
根据Javadocs,获取
, put
和删除
,而 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.
这篇关于Java类实现Map并保持插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!