两个对象的 hashCode()相同,则 equals()也一定为 true,对吗?

答案:不对

我们先看到Objec类中hashCode()方法源码

 /* @  return  a hash code value for this object.
 * @see     java.lang.Object#equals(java.lang.Object)
 * @see     java.lang.System#identityHashCode
 */
   public native int hashCode();

该方法是个native方法,因为native方法是由非Java语言实现的,所以这个方法的定义中也没有具体的实现。根据jdk文档,该方法的实现一般是“

通过将该对象的内部地址转换成一个整数来实现的

”,这个返回值就作为该对象的哈希码值返回。

再看equals源码,尤其要注意return的说明

 /* @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);
    }

hashCode值是从hash表中得来的,hash是一个函数,该函数的实现是一种算法,通过hash算法算出hash值,hash表就是hash值组成的,一共有8个位置。因此,hashCode相同的两个对象不一定equals()也为true。

举个栗子:

public static void main(String[] args) {
        String s1 = "通话";
        String s2 = "重地";

        System.out.println(s1.hashCode()+" "+s2.hashCode());
        System.out.println(s1.equals(s2));
    }

Console:

1179395 1179395
false

拓展:

两个对象值相同(x.equals(y) == true),Hashcode是否一定相同?

分两种情况:

  1. 该类未重写了equals() 方法

(x.equals(y) == true),Hashcod() 一定相同

  1. 重写了equals方法,没有重写hashCode的方法

(x.equals(y) == true),Hashcod() 不一定相同

再举个栗子说明

先定义个Person类 ,重写equals方法

static class Person{
        private String name;

        public Person(String name) {
            this.name = name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Person person = (Person) o;
            return Objects.equals(name, person.name);
        }
    }

main函数运行

public static void main(String[] args) {
        Person person = new Person("通话");
        Person person1 = new Person("通话");;
        System.out.println(person.hashCode()+" "+person1.hashCode());
        System.out.println(person.equals(person1));
    }

Console:

411631404 897913732
true

楼主也是菜鸟萌新,不对的地方欢迎大佬评论指正!

参考:
https://blog.csdn.net/meism5/article/details/89166768
https://blog.csdn.net/zouliping123456/article/details/82692127

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章