what is the logic behind hash codes. i uses this String s1 = new String("a"); String s2 = new String("b"); the hash codes for s1 and s2 are both equal. why? i also tried String s1 = "khan"; String s2 = "khan"; the hash codes for s1 and s2 are both again equal. why? plz somebody tell me the story
In reverse order, the reason the second example creates the same hash code is because Java maps all String constants to the same instance. So if you do:
The two string references point to the very same String instance, so they MUST have the same hash code. Moving to your first example, those two actually will NOT create the same hash value. String s1 has a hash code of 97 and String s2 has a hash code of 98. Keep in mind that the idea of a hash code is to quickly and easily create a unique--or nearly unique--key given an object. If you have 1000 objects that all generate different hash values, then a look-up will be very quick, since the retrieval engine will find the object on the first try. If, however, you have 1000 objects that all generate the very same hash value, a look-up will find the "bucket" for that hash value, but then will have to sequentially check each object to find the match (based on "=="). So if you override the "hashCode()" method for your object, you better make sure that you have an algorithm that "scatters" the hash values. Does that help? [ September 23, 2003: Message edited by: Wayne L Johnson ]
Originally posted by Wayne L Johnson: In reverse order, the reason the second example creates the same hash code is because Java maps all String constants to the same instance.
Actually, the reason is that the Strings represent the same value. The contract of hashCode requires that two objects for which equals returns true, hashCode must return identical values.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
The method hashCode() is overridden by String class, so it will return same hash code for the same string pattern. Also, there is constant pool in Java, if system can find "khan" already exists, s1 and s2 will be made to point to the same constant object, no new string object will be created. [ October 02, 2003: Message edited by: Bruce Lee ]