Here are my questions 1. why hash codes of str1 object and str2 object are the same? 2. why hash codes of obj1 and that of obj2 are different? 3. what does equals() method do? 4. what does operator == do? 5. why str1.equals(str2) return true? but str1==str2 returns false? 6. why array1 == array2 return false 7. and why obj1 == obj3 return false even obj3 is cloned from obj1.
Hash code will only be the same for the same object.
According to the Java api, it's not a requirement for two different objects to have distinct hash code.
The general contract of hashCode is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
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.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
Joyce [ October 13, 2004: Message edited by: Joyce Lee ]