== 对比的是栈中的值,基本数据类型是变量值,引用类型是堆中内存对象的值。
equals:object中默认也是采用== 进行比较,通常会重写
String已经重写了equals方法,如下实际上是比较两个字符串中每一个字符的内容。
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;
}
例子
public class Main {
public static void main(String[] args) {
String s1 = "111";
String s2 = new String("111");
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
}
}
字符串s1这种方式来定义字符串,实际上是在堆中的常量池里定义的,111是在常量池里的。
通过new的是在存的内存地址。
通过=号复制,赋值的就是引用地址。
equals()方法String已经重写了,所以无论怎么比较都是true。