Java ArrayList.trimToSize() – Examples
In this tutorial, we will learn about the Java ArrayList.trimToSize() method, and learn how to use this method to trim this ArrayList to be its current size, with the help of examples.
ADVERTISEMENT
trimToSize()
ArrayList.trimToSize() trims the capacity of this ArrayList instance to be the list’s current size.
Syntax
The syntax of trimToSize() method is
ArrayList.trimToSize()
Returns
The method returns void.
Example 1 – trimToSize()
In this example, we will initialize an ArrayList with four string elements "a"
, "b"
, "c"
and "d"
. We will trim the capacity of this ArrayList to its size, which is four, using ArrayList.trimToSize() method.
Java Program
import java.util.ArrayList; import java.util.Arrays; public class Example { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<String>( Arrays.asList("a", "b", "c", "d")); arrayList.trimToSize(); System.out.println("ArrayList is trimmed to its size."); } }
Output
ArrayList is trimmed to its size.
Conclusion
In this Java Tutorial, we have learnt the syntax of Java ArrayList.trimToSize() method, and also learnt how to use this method with the help of Java example programs.