This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
str1 and str2 are pointing to only one reference(same hashcode), so str1 == str2 should be true
Hashcodes have nothing to do with there references. With the Object class, they might have been originally generated from the references. With other classes, such as String, Integer, Short, Byte, etc., they have nothing to do with their reference locations.
Hash code contract states that:
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
In your example, strings are equal as per the equals() method and therefore they must return same hascode value from the hashCode() method.
Hopefully, this makes sense. Let me know if you have any questions related to what i said.
Joined: Nov 13, 2008
Just adding little more:
Objects are considered equal if they are equal as per the equals() method and not "==" operator. Equals() method(and not ==) is used by hashCode() to determine the hascode for an object.
Also, As per the contract, it is not required for two unequal objects to have different hashcode. In a bad implementation of hascode, you can have same hash code value for two different objects(their euals() method returns false). It is perfectly legal.