ArrayList

The Course
•
5 min read

An ArrayList grows as you add elements. Java provides it in the java.util library, so a classic source file begins with import java.util.ArrayList; before the class declaration. An import makes a supported library type name available; it does not copy text into your program or install a package from the internet.

ArrayList<String> means a list whose elements are Strings. The angle brackets state the element type; this is your first use of a generic type. You can use this concrete form without writing a generic class yourself. new ArrayList<>() creates an empty list. new creates an object: a value with its own data and operations. Here the object holds a growing sequence of topics. The empty angle brackets <> reuse String from the declaration on the left. Day 5 teaches you to define object types of your own.

Compare with an array

Use add(value) to append, get(index) to read, set(index,value) to replace, and size() to count elements, and remove(index) to delete an element at a position. Removal shifts later elements one position to the left. Like an array, a list starts indexing at zero; size is not a valid last index. Unlike an array, adding changes the size. For-each can visit the values without manual indexing. Do not add or remove elements while using that traversal in this course; structural changes need a deliberate strategy.

Append, replace and read a topic Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> topics = new ArrayList<>();
        topics.add("Java");
        topics.add("Reading");
        topics.set(1, "Loops");

        System.out.println(topics.size());
        System.out.println(topics.get(1));
    }
}
Check your prediction
2
Loops

add appends a new element, while set replaces one that already exists. Calling set on index=size would fail rather than append. An empty list is useful before the first add; it has size zero.

Visit a growable list Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> topics = new ArrayList<>();
        topics.add("Java");
        topics.add("Loops");

        for (String topic : topics) {
            System.out.println(topic);
        }
    }
}
Check your prediction
Java
Loops

The loop pattern is the same as an array traversal. The list owns its elements, and topic refers to the current String during each iteration. The output order follows insertion order for this ArrayList.

Your turn

Exercise

Edit a topic list

Create an ArrayList<String>. Add Variables, Loops and Methods, replace Loops with Arrays, then remove index 0. Print the size (2) and each remaining topic on its own line (Arrays, Methods).

Your workspace Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Create and edit the list.
    }
}
Hint 1: the idea

A removal shifts later elements left, so reason about indexes at the moment of each operation.

Hint 2: a first step

Perform the replacement before removing the first item; otherwise the position you planned to replace has changed.

Show one solution
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> topics = new ArrayList<>();
        topics.add("Variables");
        topics.add("Loops");
        topics.add("Methods");
        topics.set(1, "Arrays");
        topics.remove(0);

        System.out.println(topics.size());

        for (String topic : topics) {
            System.out.println(topic);
        }
    }
}
2
Arrays
Methods

Change it and explain

Draw the list after each edit. Try removing the final element of a one-element list, then check its size before reading another position. A successful removal can leave no element at index 0.

The full project will store Session objects in ArrayList<Session>. Do not jump there yet: first become comfortable distinguishing a collection’s size, an index and an element. Maps, sets, streams and collection algorithms can wait until you have a reason to use them.

Going further: number lists and removal

You can skip this section for now. The core exercise and the next lessons do not require lists of numbers.

Use ArrayList<Integer> for whole numbers. Integer is the object form of int; Java automatically converts the small int values used here when adding them. The two names are different because a list’s element type must be an object type. You do not need to write conversion code for ordinary add/get operations.

For a number list, remove has two versions: remove an index, or remove a value. Methods with the same name but different parameter types are called overloads. Integer.valueOf(30) explicitly supplies an Integer value, so Java selects the value-removal version. A plain int such as 1 selects index removal.

Integer removal has two meanings Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> values = new ArrayList<>();
        values.add(10);
        values.add(20);
        values.add(30);

        values.remove(1);
        System.out.println(values);

        values.remove(Integer.valueOf(30));
        System.out.println(values);
    }
}
Check your prediction
[10, 30]
[10]

remove(1) selects the overload taking an index. Integer.valueOf(30) selects the overload taking a value. This is not a special rule that 1 means remove the number 1. Use explicit values when the two meanings could be confused.

Was this article helpful?

Your response is saved on this device.