How to avoid items being re-ordered when put into java HashMap(放入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时如何避免重新排序项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:放入java HashMap时如何避免重新排序项目


基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01