博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
StringBuffer和StringBuilder的清空操作
阅读量:4111 次
发布时间:2019-05-25

本文共 935 字,大约阅读时间需要 3 分钟。

Collection和Map都有相应的clear操作,但是StringBuffer和StringBuilder没有,那么如何复用呢?

观察api我们知道有两种方式:

StringBuffer sb=new StringBuffer();sb.setLength(0);sb.delete(0, sb.length());

我们观察下他们的区别:

他们的实现都是在AbstractStringBuilder里进行的,详情如下:

setLength:

public void setLength(int newLength) {	if (newLength < 0)	    throw new StringIndexOutOfBoundsException(newLength);	if (newLength > value.length)	    expandCapacity(newLength);	if (count < newLength) {	    for (; count < newLength; count++)		value[count] = '\0';	} else {	    count = newLength;	}}

delete:

public AbstractStringBuilder delete(int start, int end) {	if (start < 0)	    throw new StringIndexOutOfBoundsException(start);	if (end > count)	    end = count;	if (start > end)	    throw new StringIndexOutOfBoundsException();	int len = end - start;	if (len > 0) {	    System.arraycopy(value, start+len, value, start, count-end);	    count -= len;	}	return this;}

我们发现setLength没有执行cp操作,只能重置count,因此性能相对高点。

 

转载地址:http://gcqsi.baihongyu.com/

你可能感兴趣的文章
Tree UVA - 548
查看>>
L2-006. 树的遍历
查看>>
L2-011. 玩转二叉树
查看>>
A - Buy or Build UVA - 1151
查看>>
B - Long Live the Queen SGU - 143
查看>>
Prince and Princess UVA - 10635
查看>>
ChiBi ZOJ - 3080
查看>>
L2-002. 链表去重
查看>>
L2-012. 关于堆的判断
查看>>
L2-004. 这是二叉搜索树吗
查看>>
A - Sherlock Bones Gym - 101350A
查看>>
Monkeying Around Gym - 101350F
查看>>
Snake Rana Gym - 101350G
查看>>
Flipping Coins Gym - 101606F
查看>>
Course Selection System ZOJ - 3956
查看>>
The Necklace UVA - 10054
查看>>
找连续数 HDU - 5247
查看>>
Counting Stars HDU - 6184
查看>>
Credit Card
查看>>
Winter is here
查看>>