==和equals

        == 操作比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量在堆中存储的地址是否相同,即栈中的内容是否相同。
        equals操作表示的两个变量是否是对同一个对象的引用,即堆中的内容是否相同。
        ==一般用在基本数据类型中,equals()一般比较字符串是否相等

object中的equals

        object中的equals是比较地址

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

string中的equals

        string中的equals是比较数值,先比较是否指向同一地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}

重写equals

        项目中重写equals,必须重写hashcode
        重写 hashcode() 方法有如下几个原则可以遵循:

  • 如果重写了 equals() 方法,且 equals() 方法判断相等则 hashCode() 方法也要保证必须相等。
  • 重写 hashCode() 方法算法也不能太过简单,否则哈希冲突过多。
  • 重写 hashCode() 方法算法也不能太过复杂,否则计算复杂度过高而影响性能。
            《Effective Java》书中给出的一种算法,基于 17 和 31 散列码思想的实现,如下:
    1
    2
    3
    4
    5
    public int hashCode(){
    int result = 17;
    result = 31*result + xxxx.hashCode();
    return result;
    }
            java SE 1.7简称java 1.7 对应JDK7,从1.7开始提供了java.util.Objects来重写equals 和 hashCode 方法,代码如下:
    1
    2
    3
    public int hashCode(){
    return Objects.hash(xxxx);
    }