Archive for 9月 5th, 2008

Java的字符串问题

星期五, 9月 5th, 2008

String s=”hello”;
String t=”hello”;
System.out.print(s==t);//true
?
String s=new String(”hello”);
String t=new String(”hello”);
System.out.print(s==t);//false
在两个地方,s和t的字符串内容都是hello,为什么前一个==会为true,而后一个则是false呢?

core Java的答案:

If the virtual machine would always arrange for equal strings to be shared, then you could use the == operator for testing equality. But only string constants are shared, not strings that are the result of operations like + or substring. Therefore, never use == to compare strings lest you end up with a program with the worst kind of bug—an intermittent one that seems to occur randomly.

直白一点的:

一般String常量会有一个常量池,里面放程序里出现的String常量。
当写String s=”hello”;就是声明一个叫s的引用指到常量池里那个对应的String对象上,所以你直接这么写的话,用==比较就是一样的,因为他们都指的是常量池里的那个String对象。

new的话就不一样了,后面写的那个,可以理解成用String常量池里的那个对象去调用String的构造函数,构造出一个新的String对象,这样再比较的引用肯定就不一样了,因为每次都是构造一个新的对象。