为什么Java的String对象不能改变

    技术2026-05-01  3

    Quotes: http://java.abang.com/od/javabasic/a/stringnotchange.htm 字符串String是Java程序中经常使用的一个类。但是,它有一个特殊的属性,就是一旦初始化以后,就不可再更改了。 大家都说String不可变的原因,是因为JDK源码中String类声明为final的原因。其实这不尽然,我们可以考虑这样一个问题: String类声明为fianl就成为不可变的. StringBuffer类和StringBuilder类也是被声明为final的,为什么他俩又可以变呢? 所以说这样的理解是错误的,String不可变是因为: String类自身是final的; 其次String类里面的内容也是final的,比如最重要的保存字符串的部分。 到JDK的包里面看一下String 的源代码就一目了然了: public final class String implements java.io.Serializable, 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; …… 我们还可以再对比一下String和StringBuilder的不同: private final char value[]; 那么StringBuilder呢? public StringBuilder() { super(2); } 在 AbstractStringBuilder 里面是 char value[]; AbstractStringBuilder(int capacity) { value = new char[capacity]; } 可见,这个char是可以变化的。通过一个 expandCapacity的方法进行扩充容量。
    最新回复(0)