为什么重写 equals 方法必须重写 hashcode 方法

java中的顶级父类Object的equals方法中原作者说明重写equals必须要重写hashCode

     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.

必须要重写hashCode的原因:
1.相同的对象,hashCode相同
2.不同的对象,hashCode不相同
3.不同系统,不同的对象,hashCode可能相同
所以这也是需要重写hashCode的原因

posted @ 2021-11-23 15:07  Java程序位移师  阅读(59)  评论(0)    收藏  举报