所以我的问题与声明和分配字符串有关。
我通常声明字符串的方式是执行以下操作:
String s1 = "Stackoverflow";
然后,如果我需要更改 s1 的值,我会执行以下操作:
s1 = "new value";
今天我找到了另一种方法,声明一个字符串如下:
String s2 = new String("Stackoverflow");
然后更改该值将是:
s2 = new String("new value");
我的问题是两者之间有什么区别,还是只是优先。从第四行代码看
s2 = new String ("new value");
我假设这样做会创建一个新的内存位置,然后 s2 会指向它,所以我怀疑它会被用来更改值,但我可以看到它在声明字符串时被使用。
最佳答案
来自the javadoc :
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
所以不,你没有理由不使用简单的文字。
简单地做
String s1 = "Stackoverflow";
从历史上看,此构造函数主要用于获取通过拆分较大字符串而获得的字符串的较轻副本(请参阅 this question )。现在,没有正常的理由使用它。
关于java - 字符串 [= 新字符串 vs = ""],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19322575/