Nit*_*hya 0 string immutability
我知道不可变对象是无法修改的对象.但是当我们使用函数时可以修改字符串.那么我们怎么说字符串是不可变的?这是一个问题采访.需要尽快回答
但是当我们使用函数时可以修改字符串.
不,你得到的是一个不同的字符串.例:
String a, b, c;
a = "testing 1 2 3";
b = a.substring(0, 7); // Creates new string for `b`, does NOT modify `a`
c = a.substring(8);
System.out.println(b); // "testing"
System.out.println(c); // "1 2 3", proves that `a` was not modified when we created `b`
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,字符串"testing 1 2 3"是不被修改的substring呼叫; 相反,我们只用了一个新的字符串"testing".
String对象在Java中是不可变的,因为它们不提供修改现有String对象状态的方法.它们仅提供基于现有对象的内容创建新 String对象的方法.
(当然,除非你用反射玩非常顽皮的游戏,否则上面就是这样.)