← Back to Chapters

Java ArrayList

? Java ArrayList

? Quick Overview

ArrayList is a resizable array implementation from the Java Collection Framework. It allows storing duplicate elements, maintains insertion order, and grows dynamically.

? Key Concepts

  • Part of java.util package
  • Dynamic size (no fixed length)
  • Allows duplicate values
  • Index-based access

? Syntax & Theory

ArrayList internally uses a dynamic array. When the array is full, it creates a new array with larger size and copies the elements.

? View Code Example
// Creating an ArrayList and adding elements
import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList names = new ArrayList<>();
names.add("Ram");
names.add("Shyam");
names.add("Gita");
System.out.println(names);
}
}

? Output

[Ram, Shyam, Gita]

⚙️ Common Operations

? View Code Example
// Accessing, updating and removing elements
ArrayList numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.set(1, 25);
numbers.remove(0);
System.out.println(numbers);

? Explanation

Element at index 1 is updated, and the first element is removed from the list.

? Interactive Demo: Visualize ArrayList

Type a value and add it to the list. Watch indices grow dynamically!

(Empty List)
// Java representation:
ArrayList<String> list = new ArrayList<>();

? Tips & Best Practices

  • Use generics to avoid runtime errors
  • Prefer ArrayList for fast access
  • Avoid frequent removals from the beginning

? Try It Yourself

  • Create an ArrayList of integers
  • Add five values
  • Remove the last value
  • Print the final list