I am running the code below in Hotspot JDK 1.6 on Windows XP, I ran it twice and I got the results below.
Basically, does object.hashcode() have conflicts? it doesn't seem to return the memory address in the virtual machine.
However, a comment in the JDK said that the values should be different, can anyone explain?
As far as reasonably practical, the hashCode method defined by the Object class returns different integers for different objects. (Usually this is done by converting the internal address of the object to an integer, but this implementation of the technique is not required by Java TM .)
@return a hash code value for this object. @see java.lang.Object#equals(java.lang.Object) @see java.util.Hashtable
This is the first result:
i,hashcode(): 361,9578500 i,hashcode(): 1886,9578500 conflict:1886, 361 i,hashcode(): 1905,14850080 i,hashcode(): 2185,14850080 conflict:2185, 1905 9998
This is the second result:
i,hashcode(): 361,5462872 i,hashcode(): 1886,29705835 conflict:1887, 362 i,hashcode(): 1905,9949222 i,hashcode(): 2185,2081190 conflict:2186, 1906 9998 10000
My code is:
@Test public void testAddr() { Set<Integer> s = new TreeSet<Integer>(); Map<Integer, Integer> m = new TreeMap<Integer, Integer>(); Set<Object> os = new HashSet<Object>(); for(int i = 0; i < 10000; ++i) { Object o = new Object(); os.add(o); Integer h = o.hashCode(); if((i == 361) || (i == 1886) || (i == 2185) || (i == 1905)) { System.out.println("i,hashcode(): " + i + "," + h); } if(s.contains(h)) { System.out.println("conflict:" + i + ", " + m.get(h)); } else { s.add(h); m.put(h, i); } } System.out.println(s.size()); int c = 0; for(Object o: os) { c++; } System.out.println(c); }