Java ArrayList Tutorial

The ArrayList class is a resizable array, which can be found in the java.util package.

Key Features

  • Dynamic size: Unlike arrays, ArrayList can grow and shrink dynamically as we add or remove elements.
  • Index based access: We can access elements by their index.
  • Ordered: It maintains the insertion order of elements.
  • Duplicates: It allows duplicate elements.

Example

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  {
}

Common Operations

  • add(E e): Appends the specified element to the end of this list.
  • get(int index): Returns the element at the specified position in this list.
  • set(int index, E element): Replaces the element at the specified position in this list.
  • remove(int index): Removes the element at the specified position.
  • size(): Returns the number of elements in this list.
  • clear(): Removes all of the elements from this list.