本文介绍了放入java HashMap时如何避免重新排序项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我正在创建一个新地图并将字符串推入其中(没什么大不了的)-但我注意到随着地图的增长,字符串正在重新排序.是否可以停止这种重新排序,以便地图中的项目保留放置时的顺序?
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());
}
推荐答案
如果您关心订单,可以使用 SortedMap
.实现接口的实际类(至少在大多数情况下)是 树图
.或者,LinkedHashMap
也维护它的顺序,同时仍然使用基于哈希表的容器.
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时如何避免重新排序项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!