Java equals 方法与hashcode 方法的深入解析

PS:本文使用jdk1.7
解析
1.Object类 的equals 方法


代码如下:

/**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     * <ul>
     * <li>It is <i>reflexive</i>: for any non-null reference value
     *     {@code x}, {@code x.equals(x)} should return
     *     {@code true}.
     * <li>It is <i>symmetric</i>: for any non-null reference values
     *     {@code x} and {@code y}, {@code x.equals(y)}
     *     should return {@code true} if and only if
     *     {@code y.equals(x)} returns {@code true}.
     * <li>It is <i>transitive</i>: for any non-null reference values
     *     {@code x}, {@code y}, and {@code z}, if
     *     {@code x.equals(y)} returns {@code true} and
     *     {@code y.equals(z)} returns {@code true}, then
     *     {@code x.equals(z)} should return {@code true}.
     * <li>It is <i>consistent</i>: for any non-null reference values
     *     {@code x} and {@code y}, multiple invocations of
     *     {@code x.equals(y)} consistently return {@code true}
     *     or consistently return {@code false}, provided no
     *     information used in {@code equals} comparisons on the
     *     objects is modified.
     * <li>For any non-null reference value {@code x},
     *     {@code x.equals(null)} should return {@code false}.
     * </ul>
     * <p>
     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     * <p>
     * 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.
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

看代码,Object的equals方法,采用== 进行比较,只是比较对象的引用,如果引用的对象相同,那么就返回true.
看注释,Object的equals方法,具有如下特性
1.reflexive-自反性 
 x.equals(x)  return true
2.symmetric-对称性
x.equals(y)  return true
y.equals(x)  return true
3.transitive-传递性
x.equals(y)  return true
y.equals(z)  return true
x.equals(z)  return true
4.consistent-一致性
x.equals(y)  return true //那么不管调用多少次,肯定都是返回true
5.与null的比较
x.equals(null) return false //对于none-null的x对象,每次必然返回false
6.于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.
需要注意的是,一般来说,如果重写了equals方法,都必须要重写hashcode方法,
来确保具有相同引用的对象,能够具有同样的hashcode值
好了,看到这里,我们就明白了,为什么重写了equals方法,一般来说就需要重写hashcode方法,
虽然这个不是强制性的,但是如果不能保证相同的引用对象,没有相同的hashcode,会对系统留下很大隐患
2.String类的equals方法


代码如下:

/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    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;
    }

看源码,我们可以发现,这个比较分为两部分
1.先比较是否引用同一对象
2.如果引用对象不同,是否两个String的content相同
3,String 类的hashcode 方法


代码如下:

/**
     * Returns a hash code for this string. The hash code for a
     * <code>String</code> object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using <code>int</code> arithmetic, where <code>s[i]</code> is the
     * <i>i</i>th character of the string, <code>n</code> is the length of
     * the string, and <code>^</code> indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    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;
    }

可以看到hashcode的计算公式为:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
因此,对于同一个String,得出的hashcode必然是一致的
另外,对于空的字符串,hashcode的值是0

小结
至此,我们可以对本文开头的疑问做一个小结.
1.字符串比较时用的什么方法,内部实现如何?
使用equals方法,先比较引用是否相同,后比较内容是否一致.

2.hashcode的作用,以及重写equal方法,为什么要重写hashcode方法?
hashcode是系统用来快速检索对象而使用,equals方法是用来判断引用的对象是否一致,所以,当引用对象一致时,必须要确保其hashcode也一致,因此需要重写hashcode方法来确保这个一致性

(0)

相关推荐

  • java中hashCode方法与equals方法的用法总结

    首先,想要明白hashCode的作用,必须要先知道Java中的集合. 总的来说,Java中的集合(Collection)有两类,一类是List,再有一类是Set. 前者集合内的元素是有序的,元素可以重复:后者元素无序,但元素不可重复. 那么这里就有一个比较严重的问题了:要想保证元素不重复,可两个元素是否重复应该依据什么来判断呢? 这就是Object.equals方法了.但是,如果每增加一个元素就检查一次,那么当元素很多时,后添加到集合中的元素比较的次数就非常多了. 也就是说,如果集合中现在已经有

  • java集合——Java中的equals和hashCode方法详解

    Java中的equals方法和hashCode方法是Object中的,所以每个对象都是有这两个方法的,有时候我们需要实现特定需求,可能要重写这两个方法,今天就来介绍一些这两个方法的作用. equals()和hashCode()方法是用来在同一类中做比较用的,尤其是在容器里如set存放同一类对象时用来判断放入的对象是否重复. 这里我们首先要明白一个问题: equals()相等的两个对象,hashcode()一定相等,equals()不相等的两个对象,却并不能证明他们的hashcode()不相等.换

  • 详解hashCode()和equals()的本质区别和联系

    在学习java,根据视频做实例的过程中,对equals和hashcode两个方法理解稍微深刻一点,主要是它们两个很容易混淆,容易出错,自己又通过网上的资料学习,和大家分享 equals()方法 equals是Object类提供的方法之一,众所周知,每一个java类都继承自Object类,所以说每一个对象都有equals这个方法.而我们在用这个方法时却一般都重写这个方法,why? 先看一个Object类中equals()方法的源代码: public boolean equals(Object ob

  • java中重写equals和重写hashCode()

    java中重写equals和重写hashCode() 记得在刚上初一的时候,第一堂数学课学的是集合,那时候我知道了集合是不允许重复元素存在的. hashCode 方法用于散列集合的查找,equals 方法用于判断两个对象是否相等. 为什么重写了 equals 方法,还要重写 hashCode 方法? 因为如果只重写了 equals 方法,两个对象 equals 返回了true,但是如果没有重写 hashCode 方法,集合还是会插入元素.这样集合中就出现了重复元素了. 接下来详细分析,以 Has

  • java中重写equals()方法的同时要重写hashcode()方法(详解)

    object对象中的 public boolean equals(Object obj),对于任何非空引用值 x 和 y,当且仅当 x 和 y 引用同一个对象时,此方法才返回 true: 注意:当此方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码.如下: (1) 当obj1.equals(obj2)为true时,obj1.hashCode() == obj2.hashCode()必须为true (2) 当obj

  • 关于Object中equals方法和hashCode方法判断的分析

    首先提出这样一个问题: 如果两个对象不相同,他们的hashCode值一定不相等吗? 我们都知道equals和hashCode是Object中的方法,java中每一个对象都具有这两个方法. equals(Object obj):判断两个对象是否"相同",返回true或false: public boolean equals(Object obj) { return (this == obj); } hashCode():将该对象的内部地址作为一个int值返回 public native

  • Java 超详细讲解hashCode方法

    目录 1.介绍一下hashCode方法 2.为什么需要hashCode方法? 3.hashCode(),equals()两种方法是什么关系? 4.为什么重写 equals 方法必须重写 hashcode 方法 ? 1.介绍一下hashCode方法 hashCode() 的作用是获取哈希码,也称为散列码,它实际上是返回一个int整数.这个哈希码的作用是确定该对象在哈希表中的索引位置. hashCode() 定义在JDK的Object.java中,这就意味着Java中的任何类都包含有 hashCo

  • Java equals 方法与hashcode 方法的深入解析

    PS:本文使用jdk1.7解析1.Object类 的equals 方法 复制代码 代码如下: /**     * Indicates whether some other object is "equal to" this one.     * <p>     * The {@code equals} method implements an equivalence relation     * on non-null object references:     * &l

  • 浅谈Java中的hashcode方法(推荐)

    哈希表这个数据结构想必大多数人都不陌生,而且在很多地方都会利用到hash表来提高查找效率.在Java的Object类中有一个方法: public native int hashCode(); 根据这个方法的声明可知,该方法返回一个int类型的数值,并且是本地方法,因此在Object类中并没有给出具体的实现. 为何Object类需要这样一个方法?它有什么作用呢?今天我们就来具体探讨一下hashCode方法. 一.hashCode方法的作用 对于包含容器类型的程序设计语言来说,基本上都会涉及到has

  • Java中的hashcode方法介绍

    哈希表这个数据结构想必大多数人都不陌生,而且在很多地方都会利用到hash表来提高查找效率.在Java的Object类中有一个方法: public native int hashCode(); 根据这个方法的声明可知,该方法返回一个int类型的数值,并且是本地方法,因此在Object类中并没有给出具体的实现. 为何Object类需要这样一个方法?它有什么作用呢?今天我们就来具体探讨一下hashCode方法. 一.hashCode方法的作用 对于包含容器类型的程序设计语言来说,基本上都会涉及到has

  • 为何修改equals方法时还要重写hashcode方法的原因分析

    为何修改equals方法时还要重写hashcode方法 虽然在实际开发中,我们已经使用到散列集合(如HashMap),或也单独学过散列(Hash). 但是也会有很多人像我一样,看到有些时候别人写的pojo中有对对象内hashcode函数做一个重写,这就让我重新思考为什么要这么做? 下面就让我和你一起去探索一下吧! Hash是什么? Hash就是上文说到的散列,是把任意长度的输入(又叫做预映射pre-image)通过散列算法变换成固定长度的输出,该输出就是散列值.它的理论时间复杂度是可以达到O(1

  • HashMap原理及put方法与get方法的调用过程

    HashMap的原理 HashMap的数据结构为数组+链表,以key,value的形式存值,通过调用put与get方法来存值与取值. 它内部维护了一个Entry数组,得到key的hashCode值将其移位按位与运算,然后再通过跟数组的长度-1作逻辑与运算得到一个index值来确定数据存储在Entry数组当中的位置,通过链表来解决hash冲突问题. 当发生碰撞了,对象将会储存在链表的下一个节点中. HashMap底层原理(当你put,get时内部会发生什么呢?) 接触过HashMap的小伙伴都会经

  • 探索Java中的equals()和hashCode()方法_动力节点Java学院整理

    equals()和hashCode()区别?  equals():反映的是对象或变量具体的值,即两个对象里面包含的值--可能是对象的引用,也可能是值类型的值.  hashCode():计算出对象实例的哈希码,并返回哈希码,又称为散列函数.根类Object的hashCode()方法的计算依赖于对象实例的D(内存地址),故每个Object对象的hashCode都是唯一的:当然,当对象所对应的类重写了hashCode()方法时,结果就截然不同了. 之所以有hashCode方法,是因为在批量的对象比

随机推荐