您的位置:首页 > 编程语言 > Java开发

回顾JavaSE(4)-String(3)四行代码分析String字面值对象和构造方法对象的内存分配

2016-09-21 20:16 351 查看
今天我们通过四行代码分析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个对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐