【注】昨天发现了一些StringBuffer的错误用法代码,特发此文。提醒自己。
StringBuffer自身已经提供了截取字符串的方法subString(),返回截取后的String。【注意】返回结果是String而不是StringBuffer。
StringBuffer同时也提供了获取长度方法length()。
两者使用方法同String。
【示例代码】
StringBuffer strSubmit = new StringBuffer();
//对strSubmit的操作....
【不好的写法】
batchItemBo.set("ACC_NBR_S", strSubmit.toString().substring(0, strSubmit.toString().length()-1));
【推荐写法】
batchItemBo.set("ACC_NBR_S", strSubmit.substring(0, strSubmit.length()-1));
【错误写法分析】
strSubmit.toString().substring(0, strSubmit.toString().length()-1)
1、strSubmit.toString()创建一个新的String A保存结果,并返回。
【StringBuffer的toString()方法代码如下】
public synchronized String toString() {
return new String(value, 0, count);
}
代码可看成A.substring(0, strSubmit.toString().length()-1)
2、subString()方法的第二个参数 strSubmit.toString().length()-1,会再次调用StringBuffer的toString()方法创建一个新的String B。
虽然A和B的值是一样的,但实际上创建了2个String对象来存放
代码可看成A.substring(0, B.length()-1)
3、调用String的subString()方法会第三次创建个String C来保存最终的结果。
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
【结论】整个过程除了StringBuffer本身,另外创建了3个String对象。
【推荐写法分析】
strSubmit.substring(0, strSubmit.length()-1)
1、strSubmit.length()没有创建新的对象
【StringBuffer的length()方法代码如下】
public synchronized int length() {
urn count;
}
2、strSubmit.substring()方法,创建了一个新的String对象来存放截取后的字符串。
public synchronized String substring(int start, int end) {
return super.substring(start, end);
}
super=AbstractStringBuilder
【AbstractStringBuilder的subString()方法如下】
public String substring(int start, int end) {
(start < 0)
throw new StringIndexOutOfBoundsException(start);
(end > count)
throw new StringIndexOutOfBoundsException(end);
(start > end)
throw new StringIndexOutOfBoundsException(end - start);
return new String(value, start, end - start);
}
www.2cto.com
【结论】推荐写法,整个过程除了StringBuffer本身,只创建了1个String对象。
马嘉楠 共同学习,欢迎转载。转载请注明地址【http://blog.csdn.net/majianan/article/details/6965553】,谢谢O(∩_∩)O!