String s = "hello";
String s1 = "he";
String s2 = "llo";
String s3 = "he" + "llo";
String s4 = s1 + s2;我明白s == s3是true.因为指向的是同一个字符串常量"hello".
但是为什么s4 == s是false呢?为什么又产生一个对象"hello"呢?不是内存中已经有了"hello"吗?这样的的话s4不是相当于String s4 = new String("hello")了吗?
String s1 = "he";
String s2 = "llo";
String s3 = "he" + "llo";
String s4 = s1 + s2;我明白s == s3是true.因为指向的是同一个字符串常量"hello".
但是为什么s4 == s是false呢?为什么又产生一个对象"hello"呢?不是内存中已经有了"hello"吗?这样的的话s4不是相当于String s4 = new String("hello")了吗?
比较应该用类内的equals()方法!
^_^举个例子:
String a = b + c 会变成StringBuffer tmp = new StringBuffer();
tmp.append(b);
tmp.append(c);
String a = tmp.toString();
看了你就明白了为什么s4 == s是false了.
== 比较的是引用地址是否相同,不是具体对象啊
要不比地址、要不比内容,
interhanchi(路曼曼其修远兮,吾将上下而求索.) 都说了,显然两个地址是不一样的
所以String做加法运算时,会被转化成
StringBuffer tmp = new StringBuffer();
tmp.append(b);
tmp.append(c);
String a = tmp.toString();
因为s,s3都是常量构造.而s4是由对象构造而来,所以就新建一个对象、用==比较的是 对象的引用是否相同
用equals()比较的是 对象内容是否相同
s == s3 --> s == "hello" --> true
s == s4 --> s == new String("hello") --> false