来源:https://www.zhihu.com/question/26872848
Java中默认的 equals方法实现如下:
而String类则覆写了这个方法,直观的讲就是比较字符是不是都相同。
public boolean equals(Object obj) {
return (this == obj);
}
而String类则覆写了这个方法,直观的讲就是比较字符是不是都相同。
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
待补充
二更:
"=="操作符的作用
1、用于基本数据类型的比较
2、判断引用是否指向堆内存的同一块地址。
在对string的比较中,对于常量来说,"=="和.equals()是等价的,但是一旦new出对象,就不相等了。