【发布时间】:2014-03-12 01:57:08
【问题描述】:
根据这些:
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- Difference between HashMap, LinkedHashMap and TreeMap
- 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
编辑:
我尝试使用Random 或Java 插入50 个随机数,但发现一些数据未排序。但是,它仍然能够对大多数整数进行排序。
随机结果:
...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...
【问题讨论】:
-
HashMap 不保证是未排序的。对于 0 到 11 的值,由于 HashMap 的实现方式,您将按顺序获取它们。 HashMap 通过 hashCode 将条目存储到一个数组中。 Integer 的 hashCode 与 int 值相同。
-
HashSet在底层使用HashMap也是如此。
标签: java sorting data-structures hashmap