LinkedHashMap的keySet()和values()方法的行为 [英] Behaviour of LinkedHashMap's keySet() and values() methods

查看:1685
本文介绍了LinkedHashMap的keySet()和values()方法的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

考虑我创建一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆