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

时间:2022-10-13
本文介绍了放入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时如何避免重新排序项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:hashCode、实现以及与 HashMap 的关系 下一条:为什么自定义对象不是 HashMap 的等效键?

相关文章

最新文章