StringBuffer和StringBuiler都继承自AbstractStringBuilder类,JDK1.7源码如下:
/**StringBuffer类源码*/
public final class StringBuffer extends AbstractStringBuilder
implements Serializable, CharSequence
/**StringBuilder类源码*/
public final class StringBuilder extends AbstractStringBuilder
implements Serializable, CharSequence
/**AbstractStringBuilder类源码*/
abstract class AbstractStringBuilder
implements Appendable, CharSequence
StringBuffer的构造方法,JDK1.7源码如下:
/**默认长度是16*/
public StringBuffer()
{
super(16);
}
/**可以指定初始长度*/
public StringBuffer(int i)
{
super(i);
}
/**变量长度+16*/
public StringBuffer(String s)
{
super(s.length() + 16);
append(s);
}
/**变量长度+16*/
public StringBuffer(CharSequence charsequence)
{
this(charsequence.length() + 16);
append(charsequence);
}
StringBuiler的构造方法,JDK1.7源码如下:
/**默认长度是16*/
public StringBuilder()
{
super(16);
}
/**可以指定初始长度*/
public StringBuilder(int i)
{
super(i);
}
/**变量长度+16*/
public StringBuilder(String s)
{
super(s.length() + 16);
append(s);
}
/**变量长度+16*/
public StringBuilder(CharSequence charsequence)
{
this(charsequence.length() + 16);
append(charsequence);
}
抽象类AbstractStringBuilder扩容机制,JDK1.7源码如下:
public void ensureCapacity(int i)
{
if(i > 0)
ensureCapacityInternal(i);
}
private void ensureCapacityInternal(int i)
{
if(i - value.length > 0)
expandCapacity(i);
}
void expandCapacity(int i)
{
//扩展长度j = 为原数组长度的2倍加2
int j = value.length * 2 + 2;
if(j - i < 0)
j = i;
if(j < 0)
{
//注意:这里可能会溢出,溢出后是负数,
if(i < 0)
throw new OutOfMemoryError();
j = 2147483647;
}
value = Arrays.copyOf(value, j);
}
由抽象类AbstractStringBuilder可知:StringBuffer和StringBuiler的扩容的机制在抽象类AbstractStringBuilder中实现,当发现长度不够的时候(默认长度是16),会自动进行扩容工作,扩展为原数组长度的2倍加2,创建一个新的数组,并将数组的数据复制到新数组。
StringBuffer的相关方法,JDK1.7源码如下:
public synchronized StringBuffer append(Object obj)
{
super.append(String.valueOf(obj));
return this;
}
public synchronized String substring(int i, int j)
{
return super.substring(i, j);
}
public synchronized StringBuffer replace(int i, int j, String s)
{
super.replace(i, j, s);
return this;
}
public synchronized StringBuffer delete(int i, int j)
{
super.delete(i, j);
return this;
}
public synchronized int length()
{
return count;
}
StringBuiler的相关方法,JDK1.7源码如下:
public StringBuilder append(Object obj)
{
return append(String.valueOf(obj));
}
public StringBuilder replace(int i, int j, String s)
{
super.replace(i, j, s);
return this;
}
public StringBuilder delete(int i, int j)
{
super.delete(i, j);
return this;
}
public volatile int length()
{
return super.length();
}
由源码中我们可知:
……
帮助他人,快乐自己,最后,感谢您的阅读!
所以如有纰漏或者建议,还请读者朋友们在评论区不吝指出!
……
个人网站…知识是一种宝贵的资源和财富,益发掘,更益分享…