gpt4 book ai didi

java - HashMap 应该是未排序的,但仍然根据键排序

转载 作者:搜寻专家 更新时间:2023-11-01 01:34:46 25 4
gpt4 key购买 nike

根据这些:

  1. http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
  2. Difference between HashMap, LinkedHashMap and TreeMap
  3. java beginner : How key gets sorted in hashmaps?

Java 中的 HashMap 应该是未排序的,但它是根据 Key 排序的。

我遇到了这个问题,因为我需要插入订单数据。所以,我改用了 LinkedHashMap。但我仍然很困惑为什么 HashMap 对它进行排序。

谁能解释一下?

我做了一个简单的例子来查看排序。

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

编辑:

我尝试使用 JavaRandom 插入 50 个随机数,但我发现一些数据未排序。但是,它仍然设法对大部分整数进行排序。

随机结果:

...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...

最佳答案

这是一个巧合(不是真的,而是它与哈希算法有关)。

尝试添加

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 具体说

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.

关于java - HashMap 应该是未排序的,但仍然根据键排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21750004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com