Java ArrayList

The Java ArrayList Class

The ArrayList class is the most commonly used implementation of the List interface. It uses a dynamic array to store the elements.

A standard Java array is of a fixed size. Once created, you cannot change its size. An ArrayList, however, can grow and shrink automatically as you add or remove elements.


How ArrayList Works

Internally, an ArrayList maintains an array of objects. When you create an ArrayList, it starts with an initial capacity (e.g., 10 elements).

When you add elements and the internal array becomes full, the ArrayList automatically creates a new, larger array (typically 1.5 times the old size), copies all the elements from the old array to the new one, and then adds the new element. This resizing process is handled automatically, giving the impression of a "dynamic" array.


Key Characteristics of ArrayList


When to Use ArrayList

ArrayList is the go-to choice for a List when your main requirement is storing and accessing data. If you frequently need to retrieve elements by their index and don't often add or remove elements from the middle of the list, ArrayList is the most efficient option.


ArrayList Example

Here is an example demonstrating common operations on an ArrayList.

Working with `ArrayList`

import java.util.ArrayList;
import java.util.Collections; // For sorting

public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); // Add items cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars); // Access an item System.out.println("Element at index 1: " + cars.get(1)); // Change an item cars.set(0, "Opel"); System.out.println("After changing index 0: " + cars); // Remove an item cars.remove(2); System.out.println("After removing index 2: " + cars); // Get the size System.out.println("Size of the list: " + cars.size()); // Loop through an ArrayList System.out.println("--- Looping through items ---"); for (String car : cars) { System.out.println(car); } // Sort the ArrayList Collections.sort(cars); System.out.println("Sorted list: " + cars); // Clear all items cars.clear(); System.out.println("After clearing: " + cars); } }