HashMap should be unsorted but still sorts according to key(HashMap 应该是未排序的,但仍然根据 key 排序)
问题描述
根据这些:
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- HashMap、LinkedHashMap和TreeMap的区别李>
- java初学者:如何在hashmaps中对key进行排序?
Java
中的 HashMap
应该是未排序的,但它正在根据 Key
进行排序.
The HashMap
in Java
should be unsorted but it is being sorted with respect to Key
.
我遇到了这个问题,因为我需要插入订单数据.所以,我使用 LinkedHashMap
代替.但是我仍然很困惑为什么 HashMap
对其进行排序.
I experienced this as a problem because I needed inserted-order data. So, I used LinkedHashMap
instead. But still I am confused why the HashMap
sorted it.
谁能解释一下?
我做了一个简单的例子来查看排序.
I did a simple example to view the sort.
public static void main(String[] args) {
HashMap<Integer, String> newHashMap = new HashMap<Integer, String>();
newHashMap.put(2, "First");
newHashMap.put(0, "Second");
newHashMap.put(3, "Third");
newHashMap.put(1, "Fourth");
Iterator<Entry<Integer, String>> iterator = newHashMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey());
System.out.println("Value: " + entry.getValue());
iterator.remove();
}
}
结果:
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
我尝试使用 Java
的 Random
插入 50 个随机数,但发现一些数据未排序.但是,它仍然能够对大多数整数进行排序.
I tried to insert 50 random numbers using Random
of Java
and I found some data unsorted. But, it still manages to sort most of the integers.
随机结果:
...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...
推荐答案
这是巧合(不是真的,而是与哈希算法有关).
It's a coincidence (not really, rather it has to do with the hashing algorithm).
尝试添加
newHashMap.put(-5, "Fifth");
最后一次.
输出将是
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
Key: -5
Value: Fifth
javadoc 具体说
The javadoc specifically says
这个类不保证地图的顺序;特别是,它不保证订单会随着时间的推移保持不变.
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
这篇关于HashMap 应该是未排序的,但仍然根据 key 排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HashMap 应该是未排序的,但仍然根据 key 排序
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01