BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java ArrayList trimToSize() Method

Last Updated: June 12, 2024 by Chaitanya Singh | Filed Under: java

The trimToSize() method of ArrayList class is used for memory optimization. It trims the capacity of ArrayList to the current list size. This method is useful when you want to free the unused storage space after you are done adding elements to an ArrayList, especially if you have allocated a large capacity initially but are using much less.

For example, If an arraylist is having capacity of 15 but there are only 5 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 15 to 5.

Syntax

public void trimToSize()

Example

Let’s see an example to understand how to use trimToSize() method.

import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
// Creating an ArrayList with initial capacity of 100
ArrayList<Integer> list = new ArrayList<>(100);

// Adding elements to the list
list.add(11);
list.add(22);
list.add(33);
list.add(44);
list.add(55);

System.out.println("Size of list: " + list.size());
System.out.println("Capacity before trimToSize: " + getCapacity(list));

// Trim the capacity to the current size
list.trimToSize();

System.out.println("Capacity after trimToSize: " + getCapacity(list));
}

// This method prints the current capacity of ArrayList
private static int getCapacity(ArrayList<?> list) {
try {
java.lang.reflect.Field field = ArrayList.class.getDeclaredField("elementData");
field.setAccessible(true);
return ((Object[]) field.get(list)).length;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}

Output:

Size of list: 5
Capacity before trimToSize: 100
Capacity after trimToSize: 5

In this example:

  • Initially, we have created an ArrayList with the capacity of 100.
  • Only 5 elements are added to this ArrayList.
  • After calling trimToSize() method, the capacity of ArrayList is reduced to 5, which is the current size of list.
  • This concludes that using this method can free unused storage space and can be helpful in memory optimization.
❮ Java ArrayList

Top Related Articles:

  1. Java StringBuffer toString()
  2. Java StringBuilder append() Method
  3. How to Find length of an Integer in Java
  4. Java StringBuilder lastIndexOf()
  5. Java StringBuffer delete()

Tags: Collections, Java-ArrayList

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Lathy says

    December 11, 2015 at 11:18 AM

    Hi,
    I ran your code. It prints the same result whether trimToSize() method added or removed.
    I even checked the size of the arraylist with and without trimToSize() method but in both case it remains same.
    Can you please check and update.

    Reply
    • Tony says

      October 10, 2017 at 6:14 PM

      @Lathy, There is a difference between size and capacity of an ArrayList. Size is the number of data items stored in an ArrayList. Capacity is the length of the Array that is used internally by the ArrayList. For obvious reasons, Capacity is always maintained greater than or equal to the Size. The trimToSize() method is used in situations where you know the ArrayList size is not likely to increase and you do not want to waste more memory space. Look up the implementation of ArrayList for more info.

      Reply
  2. Sudarshan says

    April 13, 2018 at 1:25 PM

    Good Day Guys,

    Can we restrict the size of the Arraylist ?
    eg : I should add only 10 objects to the arraylist.

    Reply
    • Chaitanya Singh says

      April 19, 2018 at 12:12 PM

      Hey Sudarshan, You cannot restrict the size of an ArrayList. Why you want to do that? You could have used array instead of ArrayList if you want the size to be limited.
      However if you want to achieve this in ArrayList then you have to limit the size by yourself in the code, something like this would work:

      ArrayList list = new ArrayList();
      if(list.get(10) != null)  //If there exists a 11th element
      {
           throw new ArrayIndexOutOfBoundsException();
      }
      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap