java 中==和 equals 和 hashCode 的区别

2020-08-25  本文已影响0人  有腹肌的豌豆Z

“==”

“equals()”

 public boolean equals(Object obj) {
        return (this == obj);
    }
 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;
    }

“hashCode()”

每个对象都有hashcode,对象的hashcode怎么得来的呢?
hashcode有什么作用呢?
equals方法和hashcode的关系?
为什么equals方法重写的话,建议也一起重写hashcode方法?
public class A {

    private int q=1;
    private int w=2;

    @Override
    public boolean equals(Object obj) {
        // 传入的对象obj 是否是A的实例
        if (obj instanceof A){
            // 因为是A的实例,所以强转为A。
            A obj1= (A) obj;
            if (this.q==obj1.q && this.w==obj1.w){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] arg){
        A a1=new A();
        A a2=new A();
        System.out.print(a1.hashCode()+"\n");   // 1627674070
        System.out.print(a2.hashCode()+"\n");  // 1360875712
        System.out.print(a2.equals(a1));             // true

    }

}

String重写hashode()
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;
    }
上一篇下一篇

猜你喜欢

热点阅读