Menu

Showing posts with label trimToSize method in Java. Show all posts
Showing posts with label trimToSize method in Java. Show all posts

trimToSize() in Java

trimToSize() method used to reduce the capacity of the ArrayList, StringBuffer and StringBuilder in Java. Trims the capacity of the instance(ArrayList, StringBuffer and StringBuilder) to be the list's current size. An application can use this operation to minimize the storage of those instances.
Let understand this method using a scenario, for example, we have created a StringBuffer and assign some value into it. suppose we have put "trim to size method in java" string into it. And when you will pull the length of the StringBuffer then it will return the actual size of the string, which, we have assign into it, in our case, it will return 27. But when you will fetch the capacity if the StringBuffer then it will give you output more than the length of StringBuffer, in our case it is returning 34. This means this Buffer has more capacity and could store more data into it. Since our text has the length of 27, and we don't want that extra capacity anymore in our instance then we could remove and free the extra capacity from that instance using trimToSize method. And this method will trim the capacity of an instance with the size or length of the instance.  

Here is an example code of trimToSize() method with StringBuffer

Output:
trim to size method in java, and length of StringBuffer copyText is:27
Capacity of copyText is::34
trim to size method in java, and length of StringBuffer copyText after trimToSize() is:27
Capacity of copyText after trimToSize() is::27