本文介绍了如何避免将项目放入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());
解决方案
您可以使用。实现接口的实际类(至少对于大多数情况)是。或者,也保持其顺序,同时仍然使用基于散列表的容器。
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时重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!