给出以下方法:
请问输出结果是什么?
public class TestStringEquals {
public static void main(String[] args) {
String a="123";
String b="123";
String c=new String("dfd");
String d=new String("dfd");
System.out.println(a==b);
System.out.println(a.equals(b));
System.out.println(c==d);
System.out.println(c.equals(d));
}
}
此处考察的是String的equals方法
先看下String的equals方法源码:
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
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;
}
首先比较两个对象是否是同一个对象,
如果是同一个对象,return true;
如果不是同一对象,
先看传入对象是否为String,
若为String,
则逐位比较相同下标的字符串是否相等
若全部相等,
return true;
其他场景都是false;
故运行结果是:
true
true
false
true
运行代码部分内存分析:
String a="123";//堆中常量池增加常量“123”,栈中引用类型a指向“123”的内存地址
String b="123";//堆中常量池中已有常量“123”,栈中引用类型b指向“123”的内存地址
所以a==b,并且a.equals(b)都返回true
String c=new String("dfd");//堆中新增String类型对象,常量池中增加常量“dfd”,并且新增的String对象指向常量池中的"dfd"常量,栈中引用类型c指向堆中新增的String对象的内存地址
String d=new String("dfd");//堆中新增String类型对象,常量池中已有常量“dfd”,新增的String对象指向常量池中的"dfd"常量,栈中引用类型d指向堆中新增的String对象的内存地址
c==d比较的是引用的String对象的地址,所以此处返回false,
c.equals(d)比较的是c、d的字符串数组,逐位比较后返回true