Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

ArrayList Methods

Lesson ~11 min read 8 MCQs

In simple terms: In simple terms, ArrayList methods are like special tools that let you add, remove, and change items in a flexible, resizable list in your code.

Why this matters

Imagine you're planning a surprise party for your friend, Maya. You start a guest list in your notes app. At first, it's just you and a few close friends. But then, things get complicated. Your friend Carlos can suddenly make it, so you add him. Priya has to cancel, so you remove her. Then you realize you forgot to invite Jordan, who should have been at the top of the list! You need to squeeze his name in right at the beginning.

Your notes app list is constantly changing. It grows, it shrinks, and the order gets shuffled. This is exactly what an ArrayList does in Java. It’s a dynamic list that isn’t locked into a fixed size. In this lesson, we’ll explore the built-in methods that give you the power to manage these flexible lists, just like you manage a real-world guest list.

Concept overview

flowchart TD
    A[Start: Have an ArrayList] --> B{Want to add an element?};
    B -- Yes --> C{Is an index specified?};
    B -- No --> End[Stop];
    C -- No --> D[Use add(element)];
    D --> E[Element is appended to the end of the list];
    E --> F[List size increases by 1];
    C -- Yes --> G[Use add(index, element)];
    G --> H[Element is inserted at the specified index];
    H --> I[Elements at and after the index shift right];
    I --> F;
This flowchart shows the two ways to add an element to an ArrayList. The process starts by deciding to add an element, then asks if a specific index is provided. If not, the element is appended to the end; if so, it's inserted at the index, and other elements shift. In both cases, the list size increases by one.

Core explanation

Hello there! It's Saavi. Today, we're diving into one of the most useful tools in your Java toolkit: the ArrayList.

Think back to standard arrays. They're like a row of lockers in a school hallway. Once the school is built, you can't just add more lockers in the middle of the row; the number is fixed. ArrayLists are different. They're more like a stack of foldable chairs. You can always bring in another chair or take one away. This ability to change size—what we call being mutable—is the ArrayList's superpower.

Arrays are fixed-size, like lockers; ArrayLists are dynamic, like foldable chairs.

Setting Up Your First ArrayList

Before you can use an ArrayList, you need to do two things.

First, you must tell Java where to find the ArrayList code. It lives in a package called java.util, so you need an import statement at the very top of your file:

import java.util.ArrayList;

Second, you need to declare and create it. Here's where we see something new: the angle brackets <>.

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

This creates a new, empty ArrayList that is specifically designed to hold String objects. The <String> part is called a type parameter or generic.

This is where some students get confused. Why do we need <String>? Can't we just have a plain ArrayList? While you technically can, using the type parameter is a huge help. It tells the compiler, "Hey, I only ever plan to put String objects in this list." If you accidentally try to add a number, like groceryList.add(5);, the compiler will catch your mistake immediately. Without generics, that error would only pop up when you run the program, which is much harder to debug. Always use generics!

Always use generics with ArrayLists to catch type errors at compile time.

The Core Methods You Need to Know

The AP exam focuses on a handful of essential ArrayList methods. Let's walk through them using our groceryList example. These are all on your Java Quick Reference sheet.

1. Adding Elements: add()

There are two ways to add to an ArrayList.

  • boolean add(E obj): This adds the object to the very end of the list.

    ArrayList<String> groceryList = new ArrayList<String>();
    groceryList.add("Milk");    // list is now ["Milk"]
    groceryList.add("Bread");   // list is now ["Milk", "Bread"]
    groceryList.add("Eggs");    // list is now ["Milk", "Bread", "Eggs"]

    This method technically returns true, but we almost always ignore that return value.

  • void add(int index, E obj): This inserts the object at a specific position, shifting everything else to the right.

    Imagine our list is ["Milk", "Bread", "Eggs"]. The indices are 0, 1, and 2. If we want to add "Cereal" right after "Milk" (at index 1), we do this:

    groceryList.add(1, "Cereal"); // inserts "Cereal" at index 1

    The list is now ["Milk", "Cereal", "Bread", "Eggs"]. Notice how "Bread" and "Eggs" were pushed one spot to the right to make room.

2. Getting the Size: size()

This one is straightforward. It tells you how many items are currently in the list.

System.out.println(groceryList.size()); // Prints: 4

Remember, an empty list has a size of 0.

3. Accessing Elements: get()

To read an item from the list, you use get(index). Just like with arrays, indices start at 0.

String firstItem = groceryList.get(0); // "Milk"
String thirdItem = groceryList.get(2); // "Bread"

This is a classic spot for errors. The valid indices for an ArrayList are from 0 to size() - 1. If you try to get() an element at size() or higher, your program will crash with an IndexOutOfBoundsException.

4. Replacing Elements: set()

What if you want to swap an item? You use set(index, obj). This replaces the element at a given index with a new one.

Let's say we want to buy organic eggs instead. "Eggs" is at index 3.

groceryList.set(3, "Organic Eggs");
// list is now ["Milk", "Cereal", "Bread", "Organic Eggs"]

The set method also returns the element that was replaced. This can be useful.

String oldItem = groceryList.set(0, "Almond Milk"); // oldItem is now "Milk"
// list is now ["Almond Milk", "Cereal", "Bread", "Organic Eggs"]

5. Removing Elements: remove()

Finally, to take an item out, you use remove(index). This removes the element at the specified index and shifts everything to its right one spot to the left to fill the gap.

Let's remove "Cereal" (at index 1).

groceryList.remove(1);
// list is now ["Almond Milk", "Bread", "Organic Eggs"]

Just like set, remove also returns the element that was just removed.

String removedItem = groceryList.remove(1); // removedItem is now "Bread"
// list is now ["Almond Milk", "Organic Eggs"]
System.out.println(groceryList.size()); // Prints: 2

By mastering these five methods, you can perform almost any manipulation you need on a dynamic list of data.

The `add(E obj)` method appends elements to the end of the ArrayList.

See it in action

ArrayList
Java

    
Op 0 / 0

Worked examples

Let's walk through a couple of examples to see these methods in action. It's like a play-by-play of what's happening inside the computer's memory.

Example 1

Managing a To-Do List

Problem: Aaliyah is using an ArrayList to manage her weekend chores. We need to track the state of her list after a series of operations.

Code:

ArrayList<String> chores = new ArrayList<String>();
chores.add("Clean room");
chores.add("Do laundry");
chores.add("Walk the dog");
chores.add(1, "Finish APUSH reading");
String replacedChore = chores.set(0, "Deep clean room");
chores.remove(2);

Step-by-Step Solution:

  1. ArrayList<String> chores = new ArrayList<String>();

    • What's happening
      We create an empty ArrayList named chores that will hold String objects.
    • List State
      []
    • Size
      0
  2. chores.add("Clean room");

    • What's happening
      We append "Clean room" to the end of the list.
    • List State
      ["Clean room"]
    • Size
      1
  3. chores.add("Do laundry"); and chores.add("Walk the dog");

    • What's happening
      We append two more items to the end.
    • List State
      ["Clean room", "Do laundry", "Walk the dog"]
    • Size
      3
  4. chores.add(1, "Finish APUSH reading");

    • What's happening
      We insert "Finish APUSH reading" at index 1. The existing element at index 1 ("Do laundry") and everything after it gets pushed one spot to the right.
    • List State
      ["Clean room", "Finish APUSH reading", "Do laundry", "Walk the dog"]
    • Size
      4
  5. String replacedChore = chores.set(0, "Deep clean room");

    • What's happening: We replace the element at index 0 ("Clean room") with "Deep clean room". The set method returns the old value, which is stored in the replacedChore variable.
    • List State: ["Deep clean room", "Finish APUSH reading", "Do laundry", "Walk the dog"]
    • Variable replacedChore: "Clean room"
    • Size: 4 (Note: set does not change the size!)
  6. chores.remove(2);

    • What's happening
      We remove the element at index 2, which is now "Do laundry". The element after it ("Walk the dog") shifts left to fill the gap.
    • List State
      ["Deep clean room", "Finish APUSH reading", "Walk the dog"]
    • Size
      3

Final State: The chores list contains ["Deep clean room", "Finish APUSH reading", "Walk the dog"].

Example 2

Tracking Basketball Scores

Problem: We're tracking points scored by a player in the first few minutes of a game. What is the final list and the value of lastScore?

Code:

ArrayList<Integer> points = new ArrayList<Integer>();
points.add(2);    // Layup
points.add(3);    // Three-pointer
points.add(2);    // Another layup
points.set(0, 1); // Oops, it was a free throw
points.add(1, 1); // And another free throw
int lastScore = points.remove(points.size() - 1);

Step-by-Step Solution:

  1. ArrayList<Integer> points = new ArrayList<Integer>();

    • What's happening
      We create an empty list to hold Integer objects.
    • List State
      []
  2. points.add(2); points.add(3); points.add(2);

    • What's happening
      We add three scores to the end of the list.
    • List State
      [2, 3, 2]
  3. points.set(0, 1);

    • What's happening
      We replace the element at index 0 (the first 2) with a 1.
    • List State
      [1, 3, 2]
  4. points.add(1, 1);

    • What's happening
      We insert a 1 at index 1. The 3 and 2 are shifted to the right.
    • List State
      [1, 1, 3, 2]
  5. int lastScore = points.remove(points.size() - 1);

    • Why it works: This is a very common pattern. points.size() is 4. So points.size() - 1 is 3. This line says "remove the element at the last index (index 3)".
    • What's happening: The element at index 3 is 2. This value is removed from the list and returned. The returned value (2) is then stored in the lastScore variable.
    • List State: [1, 1, 3]
    • Variable lastScore: 2

Final State: The points list is [1, 1, 3] and the lastScore variable holds the integer 2.

Tracing the `chores` ArrayList through various operations.

Try it yourself

Ready to try on your own? Think carefully about how the list changes with each step.

Problem 1: Playlist Shuffle

Predict the final state of the playlist ArrayList and the value of the nextSong variable after this code runs.

ArrayList<String> playlist = new ArrayList<String>();
playlist.add("Solar Power");
playlist.add("Good Days");
playlist.add("Levitating");
playlist.set(1, "Blinding Lights");
playlist.add(0, "As It Was");
String nextSong = playlist.remove(2);

Hint: Draw out the list on a piece of paper. After each line of code, cross out the old list and write the new one, paying close attention to the indices.

Problem 2: Class Roster

You are given an ArrayList of student names. Write the single line of code that would replace the student at index 3, "Marcus", with a new student, "Sofia".

ArrayList<String> roster = new ArrayList<String>();
roster.add("Liam");
roster.add("Priya");
roster.add("Aaliyah");
roster.add("Marcus");
roster.add("Jordan");

// Your line of code here

Hint: Are you adding a new student or replacing an existing one? Which method does that?

Tracing the `playlist` ArrayList through various operations.