Java 字符串声明差异
Java string declaration difference
在Java5.0中,下面的有什么区别?
1.
String variable = "hey";
2.
String variable = new String("hey");
这是一个很常见的关于stack overflow的问题,已经被标记为重复,所以这个答案可能可以作为答案的参考;其中许多有很高的赞成票:-
new String() vs literal string performance
Difference between string object and string literal
What is the difference between "text" and new String("text")?
无论如何,我的 2 美分,当分配一个文字时,您创建了一个对内部字符串的引用,而如果您使用 new String("...")
,您将返回一个对该字符串副本的对象引用。
第一个只是创建对象的引用。第二个创建一个全新的对象。当您使用 ==
比较两个对象时,您会注意到不同之处。
例如:
String variable1 = "hey";
String variable = "hey";
String variable2 = new String("hey");
比较时:
variable == variable1 //true
variable1 == variable2 //false
在Java5.0中,下面的有什么区别?
1.
String variable = "hey";
2.
String variable = new String("hey");
这是一个很常见的关于stack overflow的问题,已经被标记为重复,所以这个答案可能可以作为答案的参考;其中许多有很高的赞成票:-
new String() vs literal string performance
Difference between string object and string literal
What is the difference between "text" and new String("text")?
无论如何,我的 2 美分,当分配一个文字时,您创建了一个对内部字符串的引用,而如果您使用 new String("...")
,您将返回一个对该字符串副本的对象引用。
第一个只是创建对象的引用。第二个创建一个全新的对象。当您使用 ==
比较两个对象时,您会注意到不同之处。
例如:
String variable1 = "hey";
String variable = "hey";
String variable2 = new String("hey");
比较时:
variable == variable1 //true
variable1 == variable2 //false