Skip to content

Java ArrayList explained with examples

October 30, 2026 · 2 min read

An ArrayList is a list that grows and shrinks as you add and remove items. You create it with new ArrayList<>(), and it prints nicely on its own.

Add, remove, loop and sort

This program keeps prices in cents, so there are no rounding surprises:

import java.util.*;

public class Prices {
    public static void main(String[] args) {
        List<Integer> prices = new ArrayList<>();
        prices.add(1500);
        prices.add(450);
        prices.add(1200);
        prices.add(450);
        System.out.println(prices);

        prices.remove(Integer.valueOf(450));
        prices.set(0, 1600);
        System.out.println(prices);

        int total = 0;
        for (int price : prices) {
            total += price;
        }
        System.out.println("Total: " + total);

        Collections.sort(prices);
        System.out.println(prices);
        System.out.println(prices.size());
        prices.remove(0);
        System.out.println(prices);
    }
}

Output:

Output
[1500, 450, 1200, 450]
[1600, 1200, 450]
Total: 3250
[450, 1200, 1600]
3
[1200, 1600]

What each line does

  • List<Integer> is the type: a list of whole numbers. A list can't hold int directly, so you write the partner type Integer. Java converts between the two for you.
  • add(value) puts an item at the end.
  • remove(Integer.valueOf(450)) removes the first item equal to 450. The second 450 stays.
  • set(0, 1600) replaces the item at index 0. Indexes start at 0.
  • The for-each loop reads as "for each price in prices".
  • Collections.sort puts the list in order, smallest first, and changes the list itself.
  • size() is the number of items, and remove(0) removes by index, here the cheapest price.

Common mistake

With a List<Integer>, remove has two meanings. prices.remove(450) is treated as an index, not a value. On a list of three items, it stops with an IndexOutOfBoundsException.

Fix: to remove a value, wrap it with Integer.valueOf(450). To remove by position, pass the index, such as remove(0).

Also, List<int> won't compile. Use List<Integer>.

Remember to add import java.util.*; (or java.util.List and java.util.ArrayList) at the top of a classic file.

Takeaway

Use add, remove, set, size and a for-each loop for most list work, and Collections.sort to order numbers. When the list holds numbers, check whether remove gets a value or an index.