Java ArrayList Basics

High School Computer Science Notes

What is an ArrayList?

An ArrayList is a class in Java that stores a list of items. It is similar to an array, but it can grow and shrink as needed.

Why Use an ArrayList?

Importing ArrayList

Before using an ArrayList, you must import it:

import java.util.ArrayList;

Creating an ArrayList

Here is how to make an ArrayList of Strings:

ArrayList<String> fruits = new ArrayList<String>();

Here is how to make an ArrayList of Integers:

ArrayList<Integer> numbers = new ArrayList<Integer>();

Important

Notice that Java uses wrapper classes like Integer instead of int in an ArrayList.

Adding Items

Use add() to put items into the ArrayList:

fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");

Displaying the ArrayList

System.out.println(fruits);

Output:

[Apple, Banana, Orange]

Getting an Item

Use get(index) to access one item:

System.out.println(fruits.get(1));

Output:

Banana

Changing an Item

Use set(index, value) to replace an item:

fruits.set(1, "Grapes");
System.out.println(fruits);

Output:

[Apple, Grapes, Orange]

Removing an Item

Use remove(index) to delete an item:

fruits.remove(0);
System.out.println(fruits);

Output:

[Grapes, Orange]

Finding the Size

Use size() to count how many items are in the ArrayList:

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

Looping Through an ArrayList

You can use a regular for loop:

for (int i = 0; i < fruits.size(); i++) {
    System.out.println(fruits.get(i));
}

You can also use a for-each loop:

for (String fruit : fruits) {
    System.out.println(fruit);
}

Common Methods

Example Program

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> students = new ArrayList<String>();

        students.add("Alice");
        students.add("Brian");
        students.add("Carlos");

        System.out.println("Student List: " + students);
        System.out.println("First Student: " + students.get(0));

        students.set(1, "Bella");
        students.remove(2);

        System.out.println("Updated List: " + students);
        System.out.println("Number of Students: " + students.size());
    }
}

Summary