如何避免将项目放入java HashMap时重新排序
我正在创建一个新的地图并将字符串推入其中(没什么大不了的) - 但我注意到随着地图的增长,字符串正在重新排序。是否可以停止发生这种重新排序,以便地图中的项目保留放入的顺序?
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());
}
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());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您关心顺序,可以使用
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 aTreeMap
. Alternatively,LinkedHashMap
also maintains its order, while still utilizing a hashtable-based container.您可以使用
LinkedHashMap
保留它。You can keep it with
LinkedHashMap
.java中的HashMap未排序 http:// /download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html。如果您想要可预测的迭代顺序,请改用 LinkedHashMap: http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashMap.html
这里有一个关于差异的很好的讨论:LinkedHashMap的实现与HashMap有何不同?
A HashMap in java is not sorted http://download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html. If you want predictable iteration order use a LinkedHashMap instead: http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashMap.html
Heres a good discussion on the difference: How is the implementation of LinkedHashMap different from HashMap?
前面的答案是正确的,因为您应该使用维护排序的 Map 实现。 LinkedHashMap 和 SortedMap 各自执行这些操作。
然而,要点是并非所有集合都保持顺序,如果顺序对您很重要,您应该选择适当的实现。通用 HashMap 不维护顺序,不声称这样做,也不能设置这样做。
The previous answers are correct in that you should use an implementation of Map that maintains ordering. LinkedHashMap and SortedMap each do these things.
However, the takeaway point is that not all collections maintain order and if order is important to you, you should choose the appropriate implementation. Generic HashMaps do not maintain order, do not claim to do so and cannot be set to do so.