equals 与 == 比较

== :比较的是栈中的值,基本类型是变量值,引用类型是堆中内存对象的地址。

equals :在 Object 类中也是使用的 == 比较,但是其他类一般都会对该方法进行重写(重写:名称、参数列表都相同)。

Object:

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

String:

1
2
3
4
5
6
7
8
9
10
11
12
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (!COMPACT_STRINGS || this.coder == aString.coder) {
return StringLatin1.equals(value, aString.value);
}
}
return false;
}

StringLatin1:

1
2
3
4
5
6
7
8
9
10
11
public static boolean equals(byte[] value, byte[] other) {
if (value.length == other.length) {
for (int i = 0; i < value.length; i++) {
if (value[i] != other[i]) {
return false;
}
}
return true;
}
return false;
}

通过查看源码得知 String.equals() 的逻辑为:先进行 == 比较,如果指向同一个内存地址,直接返回 true ;否则调用 StringLatin1.length() 逐个比较字符数组中的字符。

测试验证:

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String("Hello");
String s3 = s2;
System.out.println(s1 == s2); // false
System.out.println(s1 == s3); // false
System.out.println(s2 == s3); // true
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true
System.out.println(s2.equals(s3)); // true
}