美文网首页
hashCode和equals方法

hashCode和equals方法

作者: 蒹葭流 | 来源:发表于2017-03-13 13:39 被阅读10次

Object类的hashCode()方法默认是native的实现,可以认为不存在性能问题。
hashCode()方法主要用来配合散列集合的一些操作,比如计算索引。
贴上String类重写的hashCode方法:

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

Object类的equals方法用于判断调用的对象是否和另一个对象相等,复写该方法许满足:

自反性:对于任何非空的x,x.equals(x)都应该返回true。
对称性:对于任何引用x和y,当且仅当x.equals(y)返回true时,y.equals(x)也应该返回true。
传递性:对于任何引用x,y,z,如果x.equals(y)返回true,y.equals(z)返回true,那么x.equals(z)也应该返回true。
一致性:如果x和y的引用没有发生变化,那么反复调用x.equals(y)的结果应该相同。
对于任何非空的引用x,x.equals(null)应该返回false。

复写是可以参考String类的equals方法:

 public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

HashMap和HashSet都是根据hashCode的值来存储对象的。
为了保证equals方法返回的结果和hashCode方法返回的结果一样,所以重写equals方法的同时也要重写hashCode方法。

相关文章

网友评论

      本文标题:hashCode和equals方法

      本文链接:https://www.haomeiwen.com/subject/npvfnttx.html