zoukankan      html  css  js  c++  java
  • 何时覆盖hashCode()和equals()方法

    The theory (for the language lawyers and the mathematically inclined):

    equals() (javadoc) must define an equivalence relation (it must be reflexivesymmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

    hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

    The relation between the two methods is:

    Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().

    In practice:

    If you override one, then you should override the other.

    Use the same set of fields that you use to compute equals() to compute hashCode().

    Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:

    public class Person {
        private String name;
        private int age;
        // ...
    
        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
                // if deriving: appendSuper(super.hashCode()).
                append(name).
                append(age).
                toHashCode();
        }
    
        @Override
        public boolean equals(Object obj) {
           if (!(obj instanceof Person))
                return false;
            if (obj == this)
                return true;
    
            Person rhs = (Person) obj;
            return new EqualsBuilder().
                // if deriving: appendSuper(super.equals(obj)).
                append(name, rhs.name).
                append(age, rhs.age).
                isEquals();
        }
    }

    Also remember:

    When using a hash-based Collection or Map such as HashSetLinkedHashSetHashMapHashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

    无论何时覆盖equals方法都需覆盖hashcode方法,并保持一致(equals为true, hashcode也一致),当需要把自己定义的类加到以hash的集合中时(HashMap会先比较hashcode, code一致时比较equals方法),如果要保持只有一个相同的实例时,需要覆盖这两方法。

  • 相关阅读:
    求原根
    koa2-router中间件来请求数据获取
    koa2 快速开始
    如何修改host
    bzoj 2480——扩展BSGS
    bzoj 4128: Matrix ——BSGS&&矩阵快速幂&&哈希
    Ubuntu 16.04LTS 安装和配置Bochs
    2019ICPC徐州网络赛 A.Who is better?——斐波那契博弈&&扩展中国剩余定理
    求十亿内所有质数的和
    MYSQL的随机查询的实现方法
  • 原文地址:https://www.cnblogs.com/daxiong225/p/9186323.html
Copyright © 2011-2022 走看看