Home » Java programming language

Java ArrayList trimToSize() Method with Example

ArrayList Class trimToSize() method: Here, we are going to learn about the trimToSize() method of ArrayList Class with its syntax and example.
Submitted by Preeti Jain, on January 19, 2020

ArrayList Class trimToSize() method

  • trimToSize() method is available in java.util package.
  • trimToSize() method is used to trims the capacity according to its current size of this Arraylist.
  • trimToSize() method is a non-static method so it is accessible with the class object and if we try to access the method with the class name then we will get an error.
  • trimToSize() method does not throw an exception at the time of trimming the size of its Arraylist.

Syntax:

    public void trimToSize();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void trimToSize() method of ArrayList.

import java.util.*;

public class TrimToSizeOfArrayList {
    public static void main(String[] args) {
        // Create an ArrayList with initial 
        // capacity of storing elements

        ArrayList < String > arr_l = new ArrayList < String > (10);

        // By using add() method is to add 
        // elements in this ArrayList
        arr_l.add("C");
        arr_l.add("C++");
        arr_l.add("JAVA");
        arr_l.add("DOTNET");
        arr_l.add("PHP");

        // By using trimToSize() method is to
        // trim the size of this ArrayList
        arr_l.trimToSize();

        // Display after trimming
        System.out.println("arr_l.trimToSize() : " + arr_l);
    }
}

Output

arr_l.trimToSize() : [C, C++, JAVA, DOTNET, PHP]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.