2016-04-03 69 views
0

我读过为了计算多维数组的哈希码,必须使用Arrays.deepHashCode()方法而不是Arrays.hashCode()方法,但我不太了解技术背后的原因。有人可以向我解释吗?当计算多维数组的散列码时使用Arrays.deepHashCode()的技术原因

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); 

结果:

two 997365 
three 312355675 

回答

3

的技术原因是,如果你只是你的阵列上调用hashCode(),你会得到一个“身份”散列码;即忽略存储在数组中的值的散列码。因此,

Object[][] one = { 
    {1, 2, 3}, 
    {11, 22, 33} 
}; 

Object[][] won = { 
    {1, 2, 3}, 
    {11, 22, 33} 
}; 

println(won.hashCode() == one.hashCode()); 

将打印false。在典型情况下,您希望onewon的散列码相等。为了达到这个目的,你需要哈希码计算来包含所有数组元素的值。

+0

非常感谢您的帮助。如果你不介意,你能否推荐一些关于学习hashcode的好资源?再次感谢您的帮助 – Thor

+1

尝试一本关于Java数据结构和算法的好书。我没有具体的建议。 –