int[] i={1,2,3}
.equals int i1[]={1,2,3}
and have different hashcode()
. When I looked into the details it calls native hashCode()
want to know how array hashcode is implemented.
Asked
Active
Viewed 3,291 times
0

passion
- 1,250
- 9
- 15

Sonia Jain
- 143
- 2
- 10
-
1Perhaps you really want to look at [java.util.Arrays.equals](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#equals-int:A-int:A-) – President James K. Polk Sep 19 '16 at 00:21
-
1`hashCode` returns different values for these two objects because they are stored in different chunks of memory, so despite holding similar content, they are different objects. See [this answer](/a/13387787/2487517) – Tibrogargan Sep 19 '16 at 00:21
1 Answers
1
The integer returned by the HashCode is different for both matrices because it is the object pointer value
System.out.println(i.hashCode()); // return 865113938
System.out.println(i1.hashCode()); // return 1442407170
Arrays.hashCode
method returns a hash code based on the contents of the specified array and as the contents of the two arrays are equal return the same value
System.out.println(Arrays.hashCode(i)); // return 30817
System.out.println(Arrays.hashCode(i1));// return 30817
And if you want to compare two arrays could use Arrays.equals
System.out.println(Arrays.equals(i, i1));//return true same content

Dev. Joel
- 1,127
- 1
- 9
- 14
-
The default hashcode is not inherently "the object pointer value". Objects can move around, but the hashcode does not change. It is, in some common JVMs a portion of the object's address is used to generate a hash. That's not the same as it being "the object pointer value". Even when the hashcode happens to match the bit pattern of one of the layers of pointers to an object, it's not useful to think of the hash as being a pointer value. – Lew Bloch Sep 19 '16 at 05:06
-
I was not looking for this I know Arrays use the below code, so here in your code you are using the Arrays hashcode. I want to understand how the normal arrays hashcode is calculated not the one in utl package public static int hashCode(int a[]) { if (a == null) return 0; int result = 1; for (int element : a) result = 31 * result + element; return result; } – Sonia Jain Sep 20 '16 at 16:41