如何避免将项目放入java HashMap时重新排序

发布于 2024-12-03 09:05:57 字数 451 浏览 0 评论 0原文

我正在创建一个新的地图并将字符串推入其中(没什么大不了的) - 但我注意到随着地图的增长,字符串正在重新排序。是否可以停止发生这种重新排序,以便地图中的项目保留放入的顺序?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

污味仙女 2024-12-10 09:05:57

如果您关心顺序,可以使用 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.

青瓷清茶倾城歌 2024-12-10 09:05:57

您可以使用LinkedHashMap保留它。

You can keep it with LinkedHashMap.

人海汹涌 2024-12-10 09:05:57

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?

花想c 2024-12-10 09:05:57

前面的答案是正确的,因为您应该使用维护排序的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文