LinkedHashMap的keySet()和values()方法的行为 [英] Behaviour of LinkedHashMap's keySet() and values() methods
问题描述
考虑我创建一个LinkedHashMap,如下所示:
Consider I create a LinkedHashMap, like the following:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
当我调用 keySet()
给我一个有序集?如果我调用 values()
,这些是否也排序了?
When I call keySet()
, does that give me an ordered set? And if I call values()
, are these ordered too?
EDIT / p>
Sry,意味着排序,不排序。
EDIT
推荐答案
LinkedHashMap
是有序,但不是排序。 TreeMap
是排序(因此也是排序)。
也就是说,你不能期望 keySet()
和 values()
的输出进行排序。实际上,JavaDoc说
First of all LinkedHashMap
is ordered but not sorted. TreeMap
is sorted (and hence ordered as well).
没有关于的顺序(事实证明,的顺序由JavaDoc保证:这是一个LinkedHashMap对象的keySet()返回的顺序吗?)这些集合,但是看着它们应该遵循底层 Map
。
That being said you can not expect the output of keySet()
and values()
to be sorted. Actually the JavaDoc says nothing about the order (as it turns out, the order is guaranteed by JavaDoc: Is the order guaranteed for the return of keySet() of a LinkedHashMap object?) of these collections, however looking at the implementation they should follow the order of underlying Map
.
要处理最近编辑你的问题:它不是合同的一部分,事实上 LinkedHashMap
没有实现 keySet()
和 values()
,但使用基类( HashMap
)版本。即使基于实现,您可以看到订单被保留,如果你想要你的应用程序是便携的,你不应该依赖它。
To address recent edit to your question: it is not part of the contract, in fact LinkedHashMap
does not even implement keySet()
and values()
but uses base classes's (HashMap
) version. Even though based on the implementation you can see the order is preserved, you should not depend on it if you want your application to be portable.
这篇关于LinkedHashMap的keySet()和values()方法的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!