In this article we are going to see the use ArrayList trimToSize
() method along with suitable examples by using Java programming language.
Java ArrayList trimToSize() Method with Example
trimToSize():
This java.util.ArrayList.trimToSize()
method is used to trim the ArrayList with the number of elements present in the ArrayList. It does not accept any parameter. It does not return anything. It does not throw any exception or errors.
Syntax:
arrayListName.trimToSize()
Where,
arrayListName
refers to the name of your ArrayList.
Let’s see different examples to understand it more clearly.
Method-1: Java ArrayList trimToSize() Method – Example with String Type ArrayList
Approach:
- Create a new ArrayList of type String.
- Add string elements into the ArrayList using the add() method.
- Display the ArrayList elements.
- Now, using the
trimToSize()
method we will set the arrayList. - Print the size of the arrayList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an ArrayList of string datatype ArrayList<String> arr1 = new ArrayList<String>(); // Adding some elements to the ArrayList arr1.add("vivo"); arr1.add("htc"); arr1.add("samsung"); arr1.add("realme"); arr1.add("nokia"); // Prints the ArrayList elements System.out.println("The elements in the ArrayList are: "+arr1); // trims the size to the number of elements arr1.trimToSize(); System.out.println("Size of ArrayList: " + arr1.size()); } }
Output: The elements in the ArrayList are: [vivo, htc, samsung, realme, nokia] Size of ArrayList: 5
Method-2: Java ArrayList trimToSize() Method – Example with Integer Type ArrayList
Approach:
- Create a new ArrayList of type Integer.
- Add Integer elements into the ArrayList using the add() method.
- Display the ArrayList elements.
- Now, using the
trimToSize()
method we will set the arrayList. - Print the size of the arrayList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an ArrayList of Integer datatype ArrayList<Integer> arr1 = new ArrayList<Integer>(); // Adding some elements to the ArrayList arr1.add(1); arr1.add(100); arr1.add(84); arr1.add(17); arr1.add(0); // Prints the ArrayList elements System.out.println("The elements in the ArrayList are: "+arr1); // trims the size to the number of elements arr1.trimToSize(); System.out.println("Size of the ArrayList: " + arr1.size()); } }
Output: The elements in the ArrayList are: [1, 100, 84, 17, 0] Size of the ArrayList: 5
Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.