This discussion is archived
6 Replies Latest reply: Nov 19, 2007 11:06 PM by 807600 RSS

StringBuffer capacity

807600 Newbie
Currently Being Moderated
Hi,

StringBuffer sb =new StringBuffer();
System.out.println(sb.capacity); // 16

sb.ensurecapacity(17);
System.out.println(sb.capacity); // 34

could any one explain, how and when the ensurecapacity method do reallocations? how the output come 34 in above problem?
  • 1. Re: StringBuffer capacity
    807600 Newbie
    Currently Being Moderated
    Have a read of the API documentation.

    http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html

    Pay attention to what it says about capacity of the buffer when you invoke the the no-arg constructor, and when you invoke ensureCapacity().
  • 2. Re: StringBuffer capacity
    807600 Newbie
    Currently Being Moderated
    Hi,

    thanks for your reply.

    what happen when the argument is greater than twice of old capacity plus two?

    that is,

    StringBuffer sb=new StringBuffer();

    sb.ensureCapacity(50);

    System.out.println(sb.capacity());

    when i run this code i got 50 as output. how?
  • 3. Re: StringBuffer capacity
    807600 Newbie
    Currently Being Moderated
    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 :)
  • 4. Re: StringBuffer capacity
    EJP Guru
    Currently Being Moderated
    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?
  • 5. Re: StringBuffer capacity
    807600 Newbie
    Currently Being Moderated
    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.
    * Twice the old capacity, plus 2.
    The minimumCapacity argument.
    oldCapacity = 16.

    If ensureCapacity(...) < 16
    then
    capacity = 16

    Twice the old capacity, plus 2.
    newCapacity = 16*2+2 = 34.

    If ensureCapacity(...) > newCapacity
    then
    newCapacity = greater value.
    else
    newCapacity = 34.

    for example,

    if ensureCapacity(50) is 50, then the newCapacity is 50...or even if it is 35 then the newCapacity is 35.
  • 6. Re: StringBuffer capacity
    807600 Newbie
    Currently Being Moderated
    sb.ensureCapacity(16);
    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 ?