w3resource

Java ArrayList.trimToSize() Method

public void trimToSize()

The trimToSize() method is used to trim a ArrayList instance to the number of elements it contains.

Package: java.util

Java Platform : Java SE 8

Syntax:

trimToSize()

Return Value:
This method does not return any value.

Pictorial presentation of ArrayList.trimToSize() Method

Java ArrayList.trimToSize() Method

Example: ArrayList.trimToSize() Method

The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly.

import java.util.*;
public class test {
  public static void main(String args[]) {
    // create an empty array list with capacity 50
    ArrayList<Integer> myArray = new ArrayList<Integer>(50);

	// Only add four elements to the ArrayList.
        myArray.add(new Integer(10));
        myArray.add(new Integer(22));
        myArray.add(new Integer(30));
		myArray.add(new Integer(40));

    // Trim the ArrayList down to size.
        myArray.trimToSize();
		
    // Print all the elements available in list
    for (Integer number : myArray) {
      System.out.println("Number = " + number);
    }
  }
} 

Output:

F:\java>javac test.java
F:\java>java test
  Number = 10
  Number = 22
  Number = 30
  Number = 40

Java Code Editor:

Previous:Java.util.ArrayList Class
Next:ensureCapacity Method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-tutorial/arraylist/arraylist_trimtosize.php