两个对象的对比 a == b 如果a跟b指向同一个对象返回true,否则返回false
Object的equals方法:
public boolean equals(Object obj) {
return (this == obj);
}
可见是等同于“==”的对比。
但是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;
}
就是如果两个String对象内部维护的字符数组值是一样的也返回true
有代码
public class TestString {
public static void main(String[] args) {
String a = "abc";
String b = "ab"+"c";
String c = new String("abc");
System.out.println(a==b); //true
System.out.println(a==c); //false
System.out.println(a.equals(c)); //true
}
}
编译后得到
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=3, locals=4, args_size=1
0: ldc #2 // String abc
2: astore_1
3: ldc #2 // String abc
5: astore_2
6: new #3 // class java/lang/String
9: dup
10: ldc #2 // String abc
12: invokespecial #4 // Method java/lang/String."<init>
":(Ljava/lang/String;)V
15: astore_3
16: getstatic #5 // Field java/lang/System.out:Ljav
a/io/PrintStream;
19: aload_1
20: aload_2
21: if_acmpne 28
24: iconst_1
25: goto 29
28: iconst_0
29: invokevirtual #6 // Method java/io/PrintStream.prin
tln:(Z)V
32: getstatic #5 // Field java/lang/System.out:Ljav
a/io/PrintStream;
35: aload_1
36: aload_3
37: if_acmpne 44
40: iconst_1
41: goto 45
44: iconst_0
45: invokevirtual #6 // Method java/io/PrintStream.prin
tln:(Z)V
48: getstatic #5 // Field java/lang/System.out:Ljav
a/io/PrintStream;
51: aload_1
52: aload_3
53: invokevirtual #7 // Method java/lang/String.equals:
(Ljava/lang/Object;)Z
56: invokevirtual #6 // Method java/io/PrintStream.prin
tln:(Z)V
59: return
LineNumberTable:
ldc:将int、float或String型常量值从常量池中推送至栈顶,String是不可变对象也就是说它的值是不能变的,String a = "a"; a = "b";是指向新对象而不是将“a”改成“b”
下面解释下代码中三个比较的结果
第一:String a = "abc"跟String b = “ab”+“c”分别是将常量池中的“abc”的引用地址存入第二和第三变量,a跟b指向常量池中同一个对象所以返回true
第二:String c = new String(“abc”)是在堆中生成一个值为“abc”的对象,再把引用地址存入第四变量,由于a跟c指向的不是同一个变量所以返回false
第三:a跟c指向不同变量,但是内部值相等所以返回true