ArrayList ClassThe 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.
ArrayList WorksInternally, 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.
ArrayListArrayList is backed by an array, retrieving an element at a specific index using the get(index) method is very fast. This is an O(1) operation.ArrayList is slow. This is because all subsequent elements need to be shifted to fill the gap or make space. This is an O(n) operation.null values: Like any List, it can store duplicate elements and null values.ArrayListArrayList 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 ExampleHere is an example demonstrating common operations on an ArrayList.
import java.util.ArrayList; import java.util.Collections; // For sortingpublic 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); } }