今天我们通过四行代码分析String字面值对象和构造方法创建对象的不同,附上内存分配图,深入理解。
首先,必须明确:
==:若是引用类型,比较的是地址值是否相同。
equals:若是引用类型,默认比较的是地址值是否相同,但Sting类重写了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 = 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;
}
然后,我们写一下代码:
<span style="white-space:pre"> </span>String s9 = new String("Hello");
String s10 = "Hello";
System.out.println("s9 == s10:" + (s9 == s10));
System.out.println("s9.equals(s10):" + s9.equals(s10));
大家可以猜一猜输出结果是啥?
第一个false,第二个true,你猜对了吗?
为什么会这样?
请看内存分配图(栈、堆、方法区-字符串常量池):
看了图,瞬间秒懂有木有。
这也是一道经典的面试题:
String构造方法创造对象可能创建2或1个对象;
String字面值创造对象可能创建1/0个对象。