日期:2014-05-20 浏览次数:20749 次
public class TestStringBuilder {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuilder string = new StringBuilder();
char[] array = new char[]{'1','2','3'};
System.out.println(string.capacity());
System.out.println(string.append(array));
System.out.println(string.append("daiwei"));
System.out.println(string.insert(3, "Hello"));
System.out.println(string.replace(4, 7, "fff")); //4~6 = fff
System.out.println(string.toString());
System.out.println(string.length());
System.out.println(string.capacity());
string.setLength(17);
System.out.println(string.length());
System.out.println(string.capacity());//为什么这里是34?
System.out.println(string.toString());
}
}
StringBuilder sb = new StringBuilder(200);
System.out.println(sb.capacity()); // 200
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2; //先以(当前容量+1)*2扩容
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) { //如果增长超过上面扩容的容量,以增长的容量进行扩容
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}