A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/java-tutorial/arraylist/arraylist_trimtosize.php below:

Java trimToSize Method - w3resource

Java ArrayList.trimToSize() MethodLast update on August 19 2022 21:50:42 (UTC/GMT +8 hours) 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

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




RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4