String 是不可变字符串,JDK源码定义String的时候其value是privite final char value[]
StringBuilder 是可变字符串,JDK源码在其父类定义的时候定义其value为 char[] value;
故String是不可变字符串,StringBuilder是可变字符串,从内存分析角度来看
若定义一个String的对象,若改变其值,则其指向的内存地址必定改变,
若定义一个StringBuilder对象,若改变其值,其内存地址未必一定改变,具体看如下两个案例。
其内存分析可见字符串生成个数分析
String b=new String("b");
for (int i=0;i<3;i++){
b+=i;
}
StringBuilder b=new StringBuilder("b");
for (int i=0;i<3;i++){
b.append(i);
}
StringBuilder构造方法如下:
/**
* Constructs a string builder initialized to the contents of the
* specified string. The initial capacity of the string builder is
* {@code 16} plus the length of the string argument.
*
* @param str the initial contents of the buffer.
*/
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
首先定义一个字符串长度+16的数组,
然后将str放到数组里面
后续调用 append 方法时首先检查其长度
/**
* Appends the string representation of the {@code int}
* argument to this sequence.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(int)},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param i an {@code int}.
* @return a reference to this object.
*/
public AbstractStringBuilder append(int i) {
if (i == Integer.MIN_VALUE) {
append("-2147483648");
return this;
}
int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
: Integer.stringSize(i);
int spaceNeeded = count + appendedLength;
ensureCapacityInternal(spaceNeeded);
Integer.getChars(i, spaceNeeded, value);
count = spaceNeeded;
return this;
}
若其所需长度与已有长度之和大于数组长度,
则调用Arrays.copyOf(value, newCapacity(minimumCapacity)),创建一个新数组,并将value的引用指向新数组
此时完成StringBuilder的扩充。
/**
* For positive values of {@code minimumCapacity}, this method
* behaves like {@code ensureCapacity}, however it is never
* synchronized.
* If {@code minimumCapacity} is non positive due to numeric
* overflow, this method throws {@code OutOfMemoryError}.
*/
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0) {
value = Arrays.copyOf(value,
newCapacity(minimumCapacity));
}
}
新数组的长度为原数组的长度的二倍加2,即(value.length << 1) + 2
private int newCapacity(int minCapacity) {
// overflow-conscious code
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}