hashCode()用于在HashMap中使用的对象数组

我有以下两个类,并希望在HashMap使用Foo1作为键。 如果它们的Foo2对象相等,则两个Foo1对象相等,如果它们的字节数组满足Arrays.equals() ,则Foo2对象相等。

我不太清楚如何为Foo1hashCode()方法。 我只需要总结每个Foo2对象的哈希Foo2还是效率低下?

 public class Foo1 { Foo2[] foo2_array; @Override public boolean equals(Object Other) { for (int i = 0; i < foo2_array.length; i++) { if (!foo2_array[i].equals(other.foo2_array[i]) return false; } return true; } @Override public int hashCode() { // what to here? } } public class Foo2 { byte[] values; @Override public boolean equals(Object other) { return Arrays.equals(values, other.values); } @Override public int hashCode() { return Arrays.hashCode(values); } } 

您的hashcode应使用与equals相同的属性集,以免破坏合同。

只需使用Foo2Arrays.hashcode

此外,你不必循环遍历每个元素你可以只使用Arrays.equals

Foo2 equals看起来像Foo1.equals

  @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Foo1 other = (Foo1) obj; if (!Arrays.equals(foo2_array, other.foo2_array)) return false; return true; } 

和hashcode类似的Foo1哈希码

  @Override public int hashCode() { return Arrays.hashCode(foo2_array); } 

同时在实现equals时,请检查null的相同引用和对象有效性。

您基本上需要一些方法,使不同的对象可能具有不同的哈希码。

因此,根据您的数据,您不一定需要总结数组中所有项的哈希值。 你基本上需要一些“足够好的东西来缩小范围”。

我会这样说:你的数据是否有任何让你怀疑你不能仅仅拿出数组中间值的哈希码? 或者也许是第一个,最后一个和中间项的组合哈希码,例如?

(这会让你怀疑你不能这样做:如果你的数据有一些特殊的function,那么某些狭窄的值子集就会作为数组中的中间元素出现。)