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 排序
基础教程推荐
- JPA惰性列表上的流 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
