日期:2014-05-20 浏览次数:20993 次
public StringBuilder(int capacity) { super(capacity); } AbstractStringBuilder(int capacity) { value = new char[capacity]; } public StringBuilder(String str) { super(str.length() + 16); append(str); } public StringBuilder append(String str) { super.append(str); return this; } public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); if (len == 0) return this; int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); str.getChars(0, len, value, count); count = newCount; return this; } 虽然走的路不一样,最终的结果是一样的。
------解决方案--------------------
public StringBuilder() { super(16); }
------解决方案--------------------
你可以看StringBuilder的源码,默认空的构造方法 是将StringBuilder的容量capacity设置为16 然后返回对象实例,以String为参数的构造方法是构造一个capacity为字符串长度+16的对象,然后将 String字符串append进去,
对于你说的这两者因为String为""长度为0,所以效果一样,不过这个多执行了一步append方法而已
public StringBuilder() { super(16); } /** * Constructs a string builder with no characters in it and an * initial capacity specified by the <code>capacity</code> argument. * * @param capacity the initial capacity. * @throws NegativeArraySizeException if the <code>capacity</code> * argument is less than <code>0</code>. */ public StringBuilder(int capacity) { super(capacity); }