Java:有没有一个容器可以有效地结合HashMap和ArrayList?
我一直发现需要一个容器,它既是HashMap
(用于快速查找键类型)又是ArrayList
(用于通过整数索引进行快速访问)
LinkedHashMap
几乎是正确的,因为它保留了一个iterable列表,但不幸的是它是一个链接的列表。。。检索第N个元素需要从1迭代到N
有没有一种集装箱适合这个账单,而我却不知怎么错过了?当其他人需要通过键和索引访问同一组数据时,他们会怎么做
你可以在下面搜索框中键入要查询的问题!
我一直发现需要一个容器,它既是HashMap
(用于快速查找键类型)又是ArrayList
(用于通过整数索引进行快速访问)
LinkedHashMap
几乎是正确的,因为它保留了一个iterable列表,但不幸的是它是一个链接的列表。。。检索第N个元素需要从1迭代到N
有没有一种集装箱适合这个账单,而我却不知怎么错过了?当其他人需要通过键和索引访问同一组数据时,他们会怎么做
# 1 楼答案
你可以自己做,但这里有一个example implemenation。相应的谷歌搜索术语是“ArrayMap”
我不确定,但也许commons collections或google collections有这样一张地图
编辑:
您可以创建一个使用arraylist实现的hashmap,也就是说,它的工作原理类似于LinkedHashMap,因为插入顺序定义了列表索引。这将提供快速的get(Index)(O(1))和get(Name)(O(1))访问,插入也将是O(1)(除非数组必须扩展),但是删除将是O(n),因为删除第一个元素需要更新所有索引
这个技巧可以通过一个映射来实现,该映射内部包含一个键->;的映射;索引,然后是数组列表
get(键)将是(没有错误检查的简单示例):
# 2 楼答案
为什么不简单地保留
HashMap
,然后按照建议使用hashMap.entrySet().toArray();
here# 3 楼答案
看看apachecommons LinkedMap
# 4 楼答案
如果您正在删除(中间)以及通过索引和键访问(这意味着索引正在更改),那么您可能会失去外观—我认为根本不可能有一个实现同时为
remove
(通过索引、键或迭代器)和get(index)
提供O(1)
。这就是为什么我们在标准API中既有LinkedList
(在iterator.remove()
中有remove(0)
)又有O(1)
中的get(index)
)和ArrayList(在O(1)
中有get(index)
)如果使用树结构而不是数组或链表(可以与基于O(1)键的读取访问结合使用,那么在
O(log n)
中可以同时删除和获取索引,但是获取键值对的索引仍然需要O(logn)如果您不想删除任何内容,或者可以使用以下索引未移位(即
remove(i)
相当于set(i, null)
),没有任何东西禁止同时使用O(1)索引和键访问-事实上,索引在这里只是第二个键,因此您可以简单地使用一个HashMap和一个ArrayList(或两个HashMap),用一个薄包装将两者结合起来Edit:因此,下面是上面最后一段中描述的
ArrayHashMap
的实现(使用“昂贵的删除”变体)。它实现下面的接口IndexedMap
。(如果您不想在此处复制+粘贴,两者也都在mygithub account中,在以后发生更改时将进行更新)以下是界面: