bingoogolapple / bingoogolapple.github.io

个人主页。同时也通过 Issues 记录学习笔记
http://www.bingoogolapple.cn
86 stars 22 forks source link

equals 与 == #119

Open bingoogolapple opened 7 years ago

bingoogolapple commented 7 years ago

重写equals()时为什么也得重写hashCode()之深度解读equals方法与hashCode方法渊源(上)

重写equals()时为什么也得重写hashCode()之深度解读equals方法与hashCode方法渊源(下)

Object 的 equals 方法默认是比较内存地址是否相等

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

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 s1 = "123";
String s2 = "123";
String s3 = new String(s1);

System.out.println("s1 == s2 : " + (s1 == s2));  // true
System.out.println("s1 == s3 : " + (s1 == s3));  // false
System.out.println("s2 == s3 : " + (s2 == s3));  // false

System.out.println("s1.equals(s2) : " + s1.equals(s2));  // true
System.out.println("s1.equals(s3) : " + s1.equals(s3));  // true
System.out.println("s2.equals(s3) : " + s2.equals(s3));  // true

Map接口的类会使用到键对象的哈希码,当我们调用put方法或者get方法对Map容器进行操作时,都是根据键对象的哈希码来计算存储位置的,因此如果我们对哈希码的获取没有相关保证,就可能会得不到预期的结果。