==和equals的区别

如果没有重写equals()方法,==和equals是相同的,因为在Object中equals方法就是通过==来实现的。

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

如果重写了equals方法,会按照我们重新写的比较逻辑来比较是否相同。

String重写了equals方法,所以str1.equals(str2)比较的是值。

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;
    }
原文地址:https://www.cnblogs.com/zhoujl-5071/p/9439510.html