是否使用内置String方法创建新字符串



据我所知,Java中的字符串是不可变的,每次我们尝试更改字符串时,Java都会在字符串池中创建新字符串并重新引用我们到这个新字符串。据说,如果我们想要改变一个String,我们应该使用String Builder或String Buffer。我的问题是:当我们使用内置的String方法,如trim()、replaceFirst()和其他改变已创建String的方法时,会发生什么?Java是否创建了一个新的String并仍然重新引用,或者我们改变了已经创建的String。

我试着用谷歌搜索,但没有找到合适的答案。可能是我的谷歌技术不是最好的:)我希望我已经把我的问题说清楚了,提前谢谢你。

字符串是不可变的——这在java中是一个事实(可能在Reflection中是例外)

  1. String对象一旦创建就不能修改
  2. 使用指向object的引用变量执行的任何操作,要么创建一个新的字符串对象,要么指向一个已经存在的不同的不可变字符串对象

不要这样做

public static void main(String[] args) throws Exception {
String immutable = "immutable";
String mutable = immutable;
String anotherObject = ("immutable" + " ").trim();
String internedCopy = anotherObject.intern();
System.out.println(immutable + " - Initial object reference");
System.out.println(mutable + " - Another reference to same object");
System.out.println(anotherObject + " - Different object with same value");
System.out.println(internedCopy + " - Reference to differently created object's internalized object");
System.out.println("Now lets try something");
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] state = (char[]) field.get(mutable);
state[0] = 'M';
System.out.println(immutable + " - Initial object reference");
System.out.println(mutable + " - Another reference to same object"); // this is the only acceptable change
System.out.println(anotherObject + " - Different object with same value");
System.out.println(internedCopy + " - Reference to differently created object's internalized object");
}

如前所述,字符串是不可变的,可以也永远不会被改变。您只能更改存储在变量中的引用。

你已经知道字符串本身没有被修改,因为当你调用这些函数时,它们返回一个新字符串,而不改变你调用函数的字符串,因为你需要做newString = oldString.trim();

当查看您提到的两个函数的源代码时,它们都创建了string。在第一个(trim())中,它只是从原始字符串的byte[]副本创建一个新的字符串,在非空白字符的范围内。第二个函数(replaceFirst())调用一些辅助函数,但是返回的String实例来自StringBuilder实例。

最新更新