内置字符串方法的用法是否会创建新字符串

问题描述

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

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

解决方法

字符串是不可变的 - 这是 Java 中的一个事实(可能是反射的例外)

  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();

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...