Please explain more; it is not usual to see the hashcode when "putting" pairs into a Map. Are you trying to get the hashcode of the whole Map? Well, of course it would be different every time you change it structurally.
The directory you installed your JDK in will contain a file called src.zip. This contains the source code for the standard Java API. You can look at this to see how each class calculates its hashcode value.
posted 11 years ago
hashCode() returns a unique value for any object on which it is called rite? I was thinking the same way for map object also. Please see the following code:
Here after the put operation it printed different values for hashCode()[It was called on the same object, map].
Quoting you, "Well, of course it would be different every time you change it structurally." How does that happen?? Does it create a new map object when we put a new object into it? Please clarify.
Thanks in advance, Maya
posted 11 years ago
Originally posted by Maya Karthik: hashCode() returns a unique value for any object on which it is called rite?
Not quite. Code that uses a hashcode will work better if all unequal objects returned a different hashcode, but in practice this is impossible (the hashcode is an int so there are only Integer.MAXVALUE possible values it can have).
Originally posted by Maya Karthik: Quoting you, "Well, of course it would be different every time you change it structurally." How does that happen?? Does it create a new map object when we put a new object into it? Please clarify.
The hashcode is used to try and tell whether two objects are equal (this is different from them being the same object). If the two objects return different hashcodes then they are definitely NOT equal. If they return the same hashcode then they MAY be equal but this is not guaranteed.
Suppose you had two Maps that contained the same objects. It would be reasonable to assume that these Maps could be considered equal, so they may return the same hashcode value. If you then added another object to one of the Maps, they could no longer be considered equal. Now, it is not a requirement that they should now return different hashcodes but it would be good if they did. Therefore when an object is added to a Map it is likely that it will recalculate its hashcode.
As I said earlier, take a look at the source code for some of the classes that implement the Map interface and you will be able to see how they calculate their hashcode and when it is likely to change.
HI Maya Nice Question which i am not aware that each adding the key/value pair in Hashmap changes the hashcode of map . In JDK HashMap.java it was written each time when add the key/value pair it does some re hashing technique to accommodate the new values even when you invoke remove() re hashing will be done again .