hashCode和Aggregation

Ing*_*ngo 2 java language-agnostic

是否存在标准元算法或如何为由其他类组成的类实现hashCode()方法的最佳实践:

class A { B b; C c;  ... }
Run Code Online (Sandbox Code Playgroud)

如果我们假设B和C在实现它们的hashCode()方面付出了一些努力,那么将As和hashcode建立在B和的基础上当然是个好主意C.但如何最好地结合它们呢?

我问这个是因为某些操作显然不适合像:

class Naive {
   B b1, b2;
   public int hashCode() { return b1.hashCode() ^ b2.hashCode(); }
}
Run Code Online (Sandbox Code Playgroud)

这会导致每个Naive对象的哈希码为0,恰好有两个相等的B对象.

nwi*_*ler 5

这是一种常见的模式,一些Eclipse插件能够生成:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((b1 == null) ? 0 : b1.hashCode());
    result = prime * result + ((b2 == null) ? 0 : b2.hashCode());
    // repeat for other attributes you want to include...

    return result;
}
Run Code Online (Sandbox Code Playgroud)

别忘了相应地编写equals()方法代码......