在一次采访中,有人问我为什么String是不可变的
我是这样回答的:
当我们在java中创建一个字符串,如string s1="hello";然后一个
对象将在字符串池(hello)中创建,s1将
指着你好。现在如果我们再次执行String s2="hello";然后
不会创建另一个对象,但s2将指向hello
因为JVM将首先检查相同的对象是否在
是否为字符串池。如果不存在,则只创建一个新的,否则不存在。
现在如果假设java允许字符串可变,那么如果我们将s1改为hello world,那么s2值也将是hello world,所以java字符串是不可变的。
谁能告诉我我的答案是对的还是错的?
字符串是不可变的有几个原因,这里是一个总结:
Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
也就是说,String的不可变性只是意味着你不能使用它的公共API改变它。实际上,您可以使用反射绕过常规API。在这里看到答案。
在你的例子中,如果String是可变的,那么考虑下面的例子:
String a="stack";
System.out.println(a);//prints stack
a.setValue("overflow");
System.out.println(a);//if mutable it would print overflow