Tho*_*hor 1 java arrays hashcode
I have read that to calculate the hashcode for multidimensional array, one has to use Arrays.deepHashCode() method instead of Arrays.hashCode() method, but I don't really understand the technical reason behind it. Could someone please explain it to me?
Object[][] one = {
{1, 2, 3},
{11, 22, 33}
};
int two = Arrays.deepHashCode(one);
int three = Arrays.hashCode(one);
System.out.println("two " + two);
System.out.println("three " + three);
Run Code Online (Sandbox Code Playgroud)
Result:
two 997365
three 312355675
Run Code Online (Sandbox Code Playgroud)
The technical reason is that if you simply you call hashCode() on the array, you will get an "identity" hashcode; i.e. a hashcode that ignores the values stored in the array. Thus
Object[][] one = {
{1, 2, 3},
{11, 22, 33}
};
Object[][] won = {
{1, 2, 3},
{11, 22, 33}
};
println(won.hashCode() == one.hashCode());
Run Code Online (Sandbox Code Playgroud)
will print false. In typical cases, you would want hash codes for one and won to be equal. To get that, you need the hash code calculation to include the values of all of the array's elements.
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |