答案就是为了安全。
那么string的底层原理是什么样的?下面是源码
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0
很容易就看出来String就是由char类型的数组封装的,内部的成员变量都是private的,也没有提供set方法来修改这些值。
在String外部无法修改String,因为自己的变量是final修饰的,所以在String内部也不能改变。所以认为String对象是不可变的
但是用反射可以改变String对象,但是一般貌似不会这么做。
本文详细介绍了 Java 中 String 类的设计原理,解释了为何 String 对象是不可变的。通过对 String 类源码的分析,揭示了其底层实现机制:通过 final 修饰的 char 数组及 private 成员变量确保了字符串的安全性和不变性。

被折叠的 条评论
为什么被折叠?



