如何避免将项目放入Java HashMap时重新排序 [英] How to avoid items being re-ordered when put into java HashMap

查看:321
本文介绍了如何避免将项目放入Java HashMap时重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个新的Map并将字符串插入(没什么大不了的) - 但我注意到随着地图的增长,字符串被重新排序。是否有可能停止发生这种重新排序,使地图中的项目保留了订单?

 地图<字符串,字符串> x = new HashMap< String,String>(); 
x.put(a,b);
x.put(a,c);
x.put(a,d);

x.put(1,2);
x.put(1,3);
x.put(1,4);

//这显示他们不按顺序...
(Map.Entry< String,String>条目:x.entrySet()){
System.out .println(IN THIS ORDER ...+ entry.getValue());


解决方案

您可以使用 SortedMap 。实现接口的实际类(至少对于大多数情况)是 TreeMap的 。或者, LinkedHashMap 也保持其顺序,同时仍然使用基于散列表的容器。

I'm creating a new Map and pushing strings into it (no big deal) -but I've noticed that the strings are being re-ordered as the map grows. Is it possible to stop this re-ordering that occurs so the items in the map retain the order the were put in with?

Map<String,String> x = new HashMap<String, String>();
x.put("a","b");
x.put("a","c");
x.put("a","d");

x.put("1","2");
x.put("1","3");
x.put("1","4");

//this shows them out of order sadly...
for (Map.Entry<String, String> entry : x.entrySet()) {
    System.out.println("IN THIS ORDER ... " + entry.getValue());
}

解决方案

If you care about order, you can use a SortedMap. The actual class which implements the interface (at least for most scenarios) is a TreeMap. Alternatively, LinkedHashMap also maintains its order, while still utilizing a hashtable-based container.

这篇关于如何避免将项目放入Java HashMap时重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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