可能的重复:
LinkedHashMap 对象的 keySet() 返回的顺序是否有保证?
考虑我创建一个 LinkedHashMap,如下所示:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
当我打电话时keySet()
,这会给我一个有序集吗?如果我打电话values()
,这些也订了吗?
EDIT
抱歉,意思是有序的,而不是排序的。
首先LinkedHashMap
is ordered但不是sorted. TreeMap
is sorted(因此ordered以及)。
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 keys and values from a LinkedHashMap object?) of these collections, however looking at the implementation they should follow the order of underlying Map
.
为了解决您问题的最新编辑:事实上,它不是合同的一部分LinkedHashMap
甚至没有实施keySet()
and values()
但使用基类的 (HashMap
) 版本。尽管根据实现您可以看到顺序被保留,但如果您希望应用程序可移植,则不应依赖它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)