StringBuffer,StringBuilder,String 类源码实现机制详解
二者区别与联系
二都都继承自父类AbstractStringBuilder
对应方法中,StringBuffer 加入了synchronized所以说是线程安全的
自动扩容
机制源于父类AbstractStringBuilder
计算最小长度
按原串双倍计算,如果小,则直接加上后串的长度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 abstract class AbstractStringBuilder implements Appendable , CharSequence { char [] value; int count; .... public AbstractStringBuilder append (String str) { if (str == null ) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0 , len, value, count); count += len; return this ; } .... private void ensureCapacityInternal (int minimumCapacity) { if (minimumCapacity - value.length > 0 ) expandCapacity(minimumCapacity); } .... void expandCapacity (int minimumCapacity) { int newCapacity = value.length * 2 + 2 ; if (newCapacity - minimumCapacity < 0 ) newCapacity = minimumCapacity; if (newCapacity < 0 ) { if (minimumCapacity < 0 ) throw new OutOfMemoryError (); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); } }
String 的不可变性 String 不可变参考
String 的不可变性在其源码中可以看出为什么不可变:
String是类型的,不可继承,防止被子类修改
其本质为char数组,采用了private final修饰,就可以避免我们手动修改数组内的内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public final class String implements java .io.Serializable, Comparable<String>, CharSequence { private final char value[]; private int hash; .... .... }