HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaVariablesData TypesOperatorsStringsArraysLists (ArrayList)Conditions (if / switch)Loops (for / while)MethodsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & List
🔁 Condition & Loop
🧩 Method & Class
Java›Lists (ArrayList)

Lists (ArrayList)

Resizable lists: add, get, size, and iterating with loops.

Simple enough for a 5-year-old to understand

Create and add to an ArrayList

Arrays have a fixed size; for growable items, use ArrayList (requires import).

Example code
1
import java.util.ArrayList;
Import ArrayList.
ImportImport ArrayList.
2
public class Main {
3
public static void main(String[] args) {
4
ArrayList<String> items = new ArrayList<>();
Empty items.
DataEmpty items.
5
items.add("apple");
Add.
CodeAdd.
6
items.add("pear");
Add.
CodeAdd.
7
System.out.println(items.get(0));
First: apple
Output / InputFirst: apple
8
System.out.println(items.size());
Size: 2
Output / InputSize: 2
9
}
10
}
ImportDataCodeOutput / Input
💡 Hint: add inserts, get(i) accesses, size() gives the size — all are methods (with parentheses).

About this topic

ArrayList is the flexible sibling of arrays: it grows automatically as you add elements and shrinks as you remove them. It is the most widely used part of Java's collection framework and has largely replaced arrays in everyday application code.

ArrayList can only hold objects; therefore, when you add a number, Java automatically converts it to its wrapper class. When defining the list, specifying the type in angle brackets — using generics — is not strictly mandatory, but without it, the compiler cannot perform type checking, and you have to write casts for every element you read.

A good habit is to define the variable with the List type and instantiate it with ArrayList. This way, switching to a different list implementation later becomes a single-line change.

What you will learn

  • Creating an ArrayList and specifying generic types
  • Using the add, get, set, and remove methods
  • Getting the number of elements with size
  • Searching with contains and indexOf
  • Iterating over the list with the enhanced for loop
  • The relationship between the List interface and ArrayList

When to use?

ArrayList is used for any dataset whose length changes: lines read from a file, records returned from a query, user selections. You will see lists instead of arrays in a large portion of everyday Java code.

If you frequently insert and remove elements from the beginning, LinkedList is more suitable; if you need unique values, HashSet; if you need key-value mappings, HashMap.

Common mistakes

Wrong

List<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);
nums.remove(10);

The remove method has two versions: the one taking an int deletes by INDEX, while the one taking an object deletes by VALUE. Since 10 is an int here, Java tries to delete index 10 and throws an "IndexOutOfBoundsException".

Correct

List<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);
nums.remove(Integer.valueOf(10));

Wrong

List<String> items = new ArrayList<>(List.of("a", "b"));
for (String s : items) {
    if (s.equals("a")) items.remove(s);
}

Removing elements from a list while iterating over it throws a "ConcurrentModificationException". Java catches this situation explicitly; for safe removal, you need to use removeIf.

Correct

List<String> items = new ArrayList<>(List.of("a", "b"));
items.removeIf(s -> s.equals("a"));

Wrong

List<String> items = List.of("a", "b");
items.add("c");

List.of produces an IMMUTABLE list; trying to add elements throws an "UnsupportedOperationException". If you want a mutable list, you need to wrap it inside an ArrayList.

Correct

List<String> items = new ArrayList<>(List.of("a", "b"));
items.add("c");

Frequently asked questions

Array or ArrayList?

If the number of elements will change, use ArrayList; if it is fixed and performance is critical, use an array. ArrayList already uses an array under the hood and creates a bigger one and copies the data when it fills up — sparing you from doing this work.

Why do we define it as a List and instantiate it with ArrayList?

Defining the variable with the interface type prevents the code from being bound to a specific implementation. If you want to switch to LinkedList tomorrow, you only change the instantiation line; the method signatures and the rest of the code remain the same.

How do I sort a list?

Using Collections.sort or the list's sort method. To sort your own classes, you need to provide a comparison criterion; you specify which field to sort by using a Comparator. Sorting modifies the list in place and does not return a copy.

Summary

ArrayList is the standard choice for data of changing length, and the variable is defined with the List interface type. Three classic traps: the ambiguity between index and value in the remove method, ConcurrentModificationException when removing elements while iterating, and lists produced by List.of being immutable.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code