This program demonstrates how to trim the capacity of an ArrayList in Java using the trimToSize() method.
The ArrayList is first initialized with some elements using the add() method. Then, the original size of the ArrayList is printed using System.out.println().
After that, the trimToSize() method is called on the ArrayList to trim the capacity to the current size of the list. The trimmed ArrayList is printed using System.out.println().
import java.util.ArrayList; import java.util.Collections; public class Capacity_ArrayList { public static void main(String[] args) { ArrayList<String> list_str= new ArrayList<String>(); list_str.add("Printer"); list_str.add("Derive"); list_str.add("Monitor"); list_str.add("Laptop"); list_str.add("Keyboard"); list_str.add("Mouse"); list_str.add("CPU"); System.out.println("Given Array List : " + list_str); System.out.println("Let trim to size the above array.. "); list_str.trimToSize(); System.out.println(list_str); } }
Given Array List : [Printer, Derive, Monitor, Laptop, Keyboard, Mouse, CPU] Let trim to size the above array.. [Printer, Derive, Monitor, Laptop, Keyboard, Mouse, CPU]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions