2019-06-20 对hashCode()、equals()、==的理解

一、Java创建的类默认继承Object,所以如果没有重写hashCode()、equals()方法,会直接用Object中的方法。

Object类中的hashCode()、equals()方法的源码。

public native int hashCode();
public boolean equals(Object obj) {
        return (this == obj);
    }

对于hashCode()方法,是一个非Java实现方法,返回的是int类型的整数。可以参考下https://xiaotao-2010.iteye.com/blog/1249006

对于equals()方法,可以看成是直接进行==处理。

所以,如果一个类没有重写hashCode()、equals()方法,

A、hashCode()跟equals()、==没有任何关系。(个人理解)

B、equals() 跟 == 是一样的效果。

二、在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;
    }

String类型重写了equals()方法,是直接比较存放的值,与 == 就不相同了。

其他的基本类型也应该是一样的,都是比较存放的值。

三、对于HashMap、HashSet等中

判定一个元素是否为重复,需要先判断元素的hashCode()是否已存在,如果不存在则为不重复;如果存在再继续比较equals(),结果为true则判定为重复元素。

原文地址:https://www.cnblogs.com/mathlin/p/11056897.html