Changes of Java 7 for HashMap in Java 5

I am not a Java expert. I just experience the changes in the output of the following programs on Java 5 and Java 7 Does anyone know what changes are in the implementation of HashMap in Java 7?

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());
        }
    }
}

Output on Java 7

D  DDD
2  222
d  ddd
1  111
0  000
b  bbb
A  AAA
B  BBB
a  aaa

Output on Java 5

0  000
1  111
a  aaa
A  AAA
B  BBB
b  bbb
2  222
D  DDD
d  ddd

Solution

Hash algorithm changed This means that you cannot rely on Java util. The iteration order of HashMap This should not come as a surprise. JDK has never given any such guarantee If the order is important to you, please use treemap or LinkedHashMap

JDK5 HashMap:

static final int hash(Object key) {
   int h;
   return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>