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.