StringBuffer的capacity()方法

StringBuffer str=new StringBuffer();
StringBuffer str1=new StringBuffer(3);
System.out.println(str.capacity()); //16
System.out.println(str1.capacity()); //8
为什么str1.capacity的结果是8?



斯蒂芬大帝
浏览 1084回答 3
3回答

慕莱坞森

你可能搞错了,输出结果应该是:163瞧瞧源码:&nbsp; &nbsp; // minimumCapacity是当前已经存储的字符长度+要追加的字符长度&nbsp; &nbsp; // value.length 是当前容量&nbsp; &nbsp; // 所以新容量=max(2*旧容量+2,追加后的字符长度)&nbsp; &nbsp; void expandCapacity(int minimumCapacity) {&nbsp; &nbsp; &nbsp; &nbsp; int newCapacity = value.length * 2 + 2;&nbsp; &nbsp; &nbsp; &nbsp; if (newCapacity - minimumCapacity < 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newCapacity = minimumCapacity;&nbsp; &nbsp; &nbsp; &nbsp; if (newCapacity < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (minimumCapacity < 0) // overflow&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new OutOfMemoryError();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newCapacity = Integer.MAX_VALUE;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; value = Arrays.copyOf(value, newCapacity);&nbsp; &nbsp; }只是在追加的时候会扩展容量,初始化时除了默认是16外,设多少就是多少。

缥缈止盈

给你看JDK 1.8中的构造方法:StringBuffer的两个构造方法,继承自父类的构造方法AbstractStringBuilder:public StringBuffer() {&nbsp; &nbsp; super(16);}public StringBuffer(int capacity) {&nbsp; &nbsp; super(capacity);}AbstractStringBuilder的构造方法:AbstractStringBuilder(int capacity) {&nbsp; &nbsp; value = new char[capacity];}&nbsp; &nbsp; &nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java