Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ensureCapacity work in Java?

StringBuffer buff1 = new StringBuffer("tuts point");

System.out.println("Old Capacity of buff1 = " + buff1.capacity());
buff1.ensureCapacity(28);
System.out.println("New Capacity of buff1 = " + buff1.capacity());

StringBuffer buff2 = new StringBuffer("compilejksde");

System.out.println("Old Capacity of buff2= " + buff2.capacity());
buff2.ensureCapacity(75);
System.out.println("New Capacity of buff2= " + buff2.capacity());
like image 760
Gauri Shankar Avatar asked Apr 10 '26 09:04

Gauri Shankar


1 Answers

The contract states the following:

Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:

  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.

So, to explain the output from your program:

Old Capacity of buff1 = 26
New Capacity of buff1 = 54  // Old capacity*2+2 (since it's larger than the argument: 28)
Old Capacity of buff2= 28
New Capacity of buff2= 75   // the argument you gave, 75 (since it's larger than 2*28+2 = 58)
like image 91
aioobe Avatar answered Apr 11 '26 22:04

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!