This content has been marked as final. Show 6 replies
Have a read of the API documentation.
Pay attention to what it says about capacity of the buffer when you invoke the the no-arg constructor, and when you invoke ensureCapacity().
thanks for your reply.
what happen when the argument is greater than twice of old capacity plus two?
StringBuffer sb=new StringBuffer();
when i run this code i got 50 as output. how?
in 10 years of using Java I've never had a need for that method.
My suggestion: forget all about it, don't worry about it, and go do something productive :)
Agreeing entirely that you don't need to know anything about it, that is also exactly what it says it will do in the Javadoc. What's the mystery?
From the javadoc for ensureCapacity(...):
Ensures that the capacity of the buffer is at least equal to the specified
minimum. If the current capacity of this string buffer is less than the
argument, then a new internal buffer is allocated with greater capacity. The
new capacity is the larger of:
* The minimumCapacity argument.The minimumCapacity argument.
* Twice the old capacity, plus 2.
oldCapacity = 16.
If ensureCapacity(...) < 16
capacity = 16
Twice the old capacity, plus 2.
newCapacity = 16*2+2 = 34.
If ensureCapacity(...) > newCapacity
newCapacity = greater value.
newCapacity = 34.
if ensureCapacity(50) is 50, then the newCapacity is 50...or even if it is 35 then the newCapacity is 35.
System.out.println(sb.capacity()); // 16
17 => 34
18 => 34
19 => 34
20 => 34
if you substitute LHS into ensureCapacity you get the RHS in the Sysout.
so... does it make sense now ?