黑马程序员技术交流社区

标题: 字符串常量池的问题 [打印本页]

作者: .Mr    时间: 2014-5-27 20:34
标题: 字符串常量池的问题
本帖最后由 .Mr 于 2014-5-28 21:59 编辑

看下面这段代码,最后一个输出不是太理解:
public static void test() {
String x = "hello";  
String y = "world";
String z = new String("helloworld");
String a = "helloworld";
System.out.println("x+y equals z:" + (x + y).equals(z)); //true,equals比较的是内容
System.out.println("a == z:" + (a == z)); //false,==比较的是实例的引用
System.out.println("a == helloworld:" + (a == ("hello" + "world")));//true
System.out.println("a == x+y:" + (a == (x + y)));      //false  比较上一个,应该为真啊,什么原因
作者: 张然龙    时间: 2014-5-27 20:41
本帖最后由 张然龙 于 2014-5-27 20:45 编辑

System.out.println(a.hashCode()==(x+y).hashCode()); //比较内存地址,结果为true,是一样的!!


这不科学.!!!!

同楼主一样寻求答案!!!


String x = "hello";  
String y = "world";
String a = "helloworld";
System.out.println(a==(x+y));    //false...
System.out.println(a.hashCode()==(x+y).hashCode());  //true...


作者: TS__likewise    时间: 2014-5-27 21:51
x+y这种方式,是不是创建了一个StringBuilder,然后把两个变量都加到StringBuilder内,再转换成String。然后就形成了一个新的String对象了。equals方法也就不适用了。 所以就FALSE了
作者: wisely    时间: 2014-5-28 12:19
x和y是对字符串常量的引用,并不是字符串常量本身,x+y在编译期是无法确定的,等到运行时,JVM会为它分配一个新的地址。比较地址,a与x+y自然不同。
只要在x和y前面加上final,两者就会变得一样。
楼上可能是正解,x+y可能默认创建了一个StringBuffer。
这是我的理解,不知道高手们同意不?
作者: wisely    时间: 2014-5-28 13:22
张然龙 发表于 2014-5-27 20:41
System.out.println(a.hashCode()==(x+y).hashCode()); //比较内存地址,结果为true,是一样的!!

这个好理解。只要a.equals(x+y)为true,那么a.hashCode()==(x+y).hashCode()就为true。比较的不是内存地址,话说版主大人你逗我呢,不会连这个都不知道吧……
作者: pk49800    时间: 2014-5-28 15:06
確實x和y加了final就是true了,但是為什麼呢
作者: 张然龙    时间: 2014-5-28 15:49
wisely 发表于 2014-5-28 13:22
这个好理解。只要a.equals(x+y)为true,那么a.hashCode()==(x+y).hashCode()就为true。比较的不是内存地 ...

我当然知道equals比较的是内容不是地址, 但是你看清楚,  我写的不是equals,我写的是==
作者: .Mr    时间: 2014-5-28 21:59
张然龙 发表于 2014-5-27 20:41
System.out.println(a.hashCode()==(x+y).hashCode()); //比较内存地址,结果为true,是一样的!!

是啊,hashcode是TRUE,可能解释的就是2楼的这种解释了。
作者: 13556793092    时间: 2014-5-29 18:39
从打印结果给你详细解释了啊:
public static void test() {
String x = "hello";  
String y = "world";
String z = new String("helloworld");
String a = "helloworld"; //1.(x + y).equals(z)   x+y=helloworld  z=helloworld 内容相同  返回true
System.out.println("x+y equals z:" + (x + y).equals(z))
//2.a对象个z对象不是同一个对象,地址值当然不同,返回false
System.out.println("a == z:" + (a == z))
//3.道理同1
System.out.println("a == helloworld:" + (a == ("hello" + "world")));//true
//4.a在创建时在字符常量池中有自己的地址,x,y也同样有自己的地址,这里x+y只是把x和y的字符创内容相加,x和y以及z都有各自的地址值,因此不可能相等
System.out.println("a == x+y:" + (a == (x + y)));


作者: 363758086ed    时间: 2014-5-29 20:41
楼上说的对




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2