【发布时间】:2019-03-02 17:29:35
【问题描述】:
每个字符串缓冲区都有一个容量。只要字符串缓冲区包含的字符序列的长度不超过容量,就不需要分配新的内部缓冲区数组。如果内部缓冲区溢出,它会自动变大。
根据我的理解,这意味着如果我们对一个字符串缓冲区使用append方法并且给定字符串的长度超过了字符串缓冲区的容量,JVM会自动分配一些更大的内存给一个新的字符串缓冲区并将旧的字符串缓冲区与给定的字符串一起存储。但是,既然如此,旧的字符串缓冲区和新的字符串缓冲区怎么可能具有相同的引用,如下所示。附加的字符串大于 16 字节,因此这将强制 JVM 为新的字符串缓冲区分配一些新内存。
public class test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("initial value");
System.out.println("before: the reference is " + System.identityHashCode(sb));
sb.append(" - this message is append through sb and this message is longer than 16 bytes");
System.out.println("after: the reference is " + System.identityHashCode(sb));
}
}
输出
before: the reference is 511833308
after: the reference is 511833308
【问题讨论】:
-
您自己发布了它:“...分配一个新的 internal 缓冲区数组...” [:-) (并注意
hashCode的文档:可能或可能不被实现为对象内存地址的某个函数)
标签: java reference stringbuffer