In general, a contract for a Java hash code only requires that:
- Whenever it is called by the same object more than once during the execution of a Java application, the hashCode method must consistently return the same integer if the information used in equal comparisons with the object does not change. This integer should not remain consistent with one execution of the application on another execution of the same application.
- If two objects are equal in accordance with the equals (Object) method, then calling the hashCode method for each of the two objects should lead to the same integer result.
- It is not required that if two objects are unequal according to the equals method (java.lang.Object), then calling the hashCode method for each of the two objects must produce different integer results. However, the programmer should be aware that creating separate integer results for unequal objects can improve the performance of hash tables.
(From Java documentation on Object#hashCode )
Here you have two integer arrays that are not equal (for example, a.equals(b) => false ), but they are not (see the third point) needed to return unequal hash codes.
Also note that your code will work if you use Arrays.equals instead of Object#equals , as follows. Please note that Arrays.equals checks that "both arrays contain the same number of elements, and all the corresponding pairs of elements in two arrays are equal."
int[] intArray = { 1, 2 }; out.println(intArray.getClass().hashCode()); int[] int2Array = { 1, 2 }; out.println(int2Array.getClass().hashCode()); out.println(Arrays.equals(intArray, int2Array));
See http://www.ideone.com/HaysD for a working example.
source share