我不是Java专家,只是体验Java 5和Java 7上以下程序输出的变化.任何人都知道Java 7中HashMap实现的变化是什么吗?
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "111");
map.put("a", "aaa");
map.put("A", "AAA");
map.put("D", "DDD");
map.put("d", "ddd");
map.put("0", "000");
map.put("B", "BBB");
map.put("b", "bbb");
map.put("2", "222");
for(Map.Entry<String, String> entry : map.entrySet()){
System.out.println(entry.getKey()+ " "+entry.getValue());
}
}
}
Run Code Online (Sandbox Code Playgroud)
Java 7上的输出
D DDD
2 222
d ddd
1 111
0 000
b bbb
A AAA
B BBB
a aaa
Run Code Online (Sandbox Code Playgroud)
Java 5上的输出
0 000
1 111
a aaa
A AAA
B BBB
b bbb
2 222
D DDD
d ddd
Run Code Online (Sandbox Code Playgroud)
散列算法已更改.这意味着您不能依赖迭代顺序java.util.HashMap.这不应该让人感到意外,JDK从来没有给出任何这样的保证.如果订单对您很重要,请使用TreeMap或LinkedHashMap.
JDK5 HashMap:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
Run Code Online (Sandbox Code Playgroud)
JDK7 HashMap:
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1926 次 |
| 最近记录: |