If the hashCode() method is not overridden, what will be the result of invoking hashCode() on any object in Java?
|
Typically, hashCode() just returns the object's address in memory if you don't overload it. From 1:
|
|||||
|
The implementation of
|
|||||||||
|
If hashcode is not overriden you will call Object's hashcode, here is an excerpt from its javadoc:
|
|||
|
A hashcode is useful for storing an object in a collection, such as a hashset. By allowing an Object to define a Hashcode as something unique it allows the algorithm of the HashSet to work effectively. Object itself uses the Object's address in memory, which is very unique, but may not be very useful if two different objects (for example two identical strings) should be considered the same, even if they are duplicated in memory. |
|||
|
the default hashcode implementation gives the internal address of the object in the jvm, as a 32 bits integer. Thus, two different (in memory) objects will have different hashcodes. This is consistent with the default implementation of equals. If you want to override equals for your objects, you will have to adapt hashCode so that they are consistent. See http://www.ibm.com/developerworks/java/library/j-jtp05273.html for a good overview. |
|||
|
Two objects with different hash code must not be equal with regard to equals()
However, two objects that are not equal with regard to equals() can have the same hash code. Storing these objects in a set or map will become less efficient if many objects have the same hash code. |
|||
|
returns 6 digit hex number. This is usually the memory location of the slot where the object is addressed. From an algorithmic per-se, I guess JDK does double hashing (native implementation) which is one of the best hashing functions for open addressing. This double hashing scheme highly reduces the possibility of collisions. The following post will give a supportive idea - Java - HashMap confusion about collision handling and the get() method |
||||
|
You should try to implement the hash code so that different objects will give different results. I don't think there is a standard way of doing this. Read this article for some information. |
|||
|
Not really an answer but adding to my earlier comment
I tried to do something like this:
But the hashcode indeed doesn't change... can someone tell me how Sun's JDK actually implements Obect.hashcode? |
|||||||||
|