Fiveable

💻AP Computer Science A Unit 4 Review

QR code for AP Computer Science A practice questions

4.8 ArrayList Methods

💻AP Computer Science A
Unit 4 Review

4.8 ArrayList Methods

Written by the Fiveable Content Team • Last updated September 2025
Verified for the 2026 exam
Verified for the 2026 examWritten by the Fiveable Content Team • Last updated September 2025
Pep mascot

ArrayList methods provide the essential operations for working with dynamic collections in Java. These methods handle common tasks like adding, removing, and accessing elements, making ArrayLists much more powerful and flexible than regular arrays. Understanding these core methods is crucial because they form the foundation for data manipulation in most Java programs.

The ArrayList API is designed around practical programming needs. Each method solves a specific problem that programmers face when working with collections. Rather than memorizing every method, focus on understanding the patterns - methods for adding data, removing data, accessing data, and searching. Once you grasp these categories, you can predict what methods exist and how they work.

  • Major concepts: Core ArrayList API methods, modification operations, access methods, search functionality
  • Why this matters for AP: Essential for FRQ 3 (Array/ArrayList), method calls appear in all FRQ types
  • Common pitfalls: Confusing add() overloads, forgetting return types, mixing up remove() versions
  • Key vocabulary: API methods, overloaded methods, index-based operations, element-based operations
  • Prereqs: ArrayList basics, understanding method signatures, familiarity with return types

Key Concepts

Pep mascot
more resources to help you study

The Core ArrayList Toolkit

When you're working with ArrayLists in real projects, there are about eight methods that do 90% of the heavy lifting. These aren't random - they represent the fundamental operations you need for managing dynamic collections.

The essential methods break down into three categories: adding data (add()), removing data (remove()), and getting information (get(), size(), contains()). Each category handles different aspects of collection management.

Here's what makes these methods powerful: they handle all the complex array management behind the scenes. When you call add(), you don't have to worry about whether there's space - the ArrayList figures that out.

Method Overloading in ArrayList

ArrayList methods use overloading extensively, which means the same method name can do different things depending on what parameters you pass. This is super practical because it lets you use intuitive method names regardless of how you want to perform the operation.

For example, add() has two versions: add(element) adds to the end, while add(index, element) inserts at a specific position. Same concept, different execution based on your needs.

This pattern repeats throughout the ArrayList API. Understanding overloading helps you predict how methods work even when you haven't memorized every variation.

Index-Based vs Element-Based Operations

Some ArrayList methods work with indices (positions), while others work with actual elements (values). This distinction is crucial for choosing the right method for your situation.

Index-based methods like get(2) or remove(0) are perfect when you know exactly where your data is located. Element-based methods like contains("apple") or remove("banana") are better when you're searching for specific values.

The AP exam loves testing whether you understand this difference, especially in scenarios where both approaches could work but one is more appropriate.

Return Values and Side Effects

Every ArrayList method either returns information or modifies the list (or both). Understanding what each method gives you back is essential for writing correct code.

Methods like get() and contains() return information without changing the list. Methods like add() and remove() modify the list and may also return useful information about what happened.

Some methods like set() do both - they modify the list and return the old value that was replaced.

Code Examples

Adding Elements - Different Approaches

import java.util.ArrayList;

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

        // add(element) - adds to the end
        playlist.add("Song A");
        playlist.add("Song B");
        playlist.add("Song C");
        System.out.println("After basic adds: " + playlist);

        // add(index, element) - inserts at specific position
        playlist.add(1, "New Song");  // Inserts at index 1, shifts others right
        System.out.println("After insertion: " + playlist);

        // Practical example: building a queue vs inserting priority items
        ArrayList<String> queue = new ArrayList<String>();
        queue.add("Regular task 1");
        queue.add("Regular task 2");
        queue.add(0, "URGENT TASK");  // Insert at front for priority
        System.out.println("Priority queue: " + queue);
    }
}

Notice how add() without an index always goes to the end, while add(index, element) lets you insert anywhere. The insertion version shifts existing elements to make room, which is exactly what you want for most real-world scenarios.

Accessing and Modifying Data

// Example: Working with student grades
public class GradeManager {
    public static void main(String[] args) {
        ArrayList<Integer> grades = new ArrayList<Integer>();
        grades.add(85);
        grades.add(92);
        grades.add(78);
        grades.add(96);

        // get(index) - retrieves without changing
        int firstGrade = grades.get(0);
        System.out.println("First grade: " + firstGrade);

        // set(index, element) - replaces and returns old value
        int oldGrade = grades.set(2, 88);  // Changes 78 to 88
        System.out.println("Changed grade " + oldGrade + " to 88");
        System.out.println("Updated grades: " + grades);

        // size() - tells you how many elements
        System.out.println("Total grades: " + grades.size());

        // Practical use: updating records
        for (int i = 0; i < grades.size(); i++) {
            if (grades.get(i) < 80) {
                grades.set(i, grades.get(i) + 5);  // Curve up low grades
            }
        }
        System.out.println("After curve: " + grades);
    }
}

The set() method is particularly useful because it returns the old value, letting you see what was replaced. This is perfect for scenarios where you need to track changes.

Removing Elements - Two Different Ways

// Example: Managing a shopping cart
public class ShoppingCart {
    public static void main(String[] args) {
        ArrayList<String> cart = new ArrayList<String>();
        cart.add("Apples");
        cart.add("Bread");
        cart.add("Milk");
        cart.add("Cookies");
        cart.add("Bread");  // Duplicate item

        System.out.println("Original cart: " + cart);

        // remove(index) - removes by position, returns the removed element
        String removedItem = cart.remove(0);  // Removes first item
        System.out.println("Removed by index: " + removedItem);
        System.out.println("Cart after index removal: " + cart);

        // remove(element) - removes by value, returns boolean success
        boolean wasRemoved = cart.remove("Bread");  // Removes first occurrence
        System.out.println("Successfully removed Bread: " + wasRemoved);
        System.out.println("Cart after element removal: " + cart);

        // Notice: only removes FIRST occurrence of duplicate
        System.out.println("Bread still in cart: " + cart.contains("Bread"));
    }
}

The two remove() methods serve different purposes. Index-based removal is precise but requires knowing position. Element-based removal is more intuitive but only removes the first match.

Search and Information Methods

// Example: Library book management
public class LibrarySystem {
    public static void main(String[] args) {
        ArrayList<String> books = new ArrayList<String>();
        books.add("Java Programming");
        books.add("Data Structures");
        books.add("Web Development");
        books.add("Mobile Apps");

        // contains(element) - checks if element exists
        boolean hasJavaBook = books.contains("Java Programming");
        System.out.println("Has Java book: " + hasJavaBook);

        // indexOf(element) - finds position of element
        int position = books.indexOf("Web Development");
        System.out.println("Web Development at index: " + position);

        // indexOf returns -1 if not found
        int notFound = books.indexOf("Machine Learning");
        System.out.println("Machine Learning index: " + notFound);  // -1

        // isEmpty() - checks if list has no elements
        System.out.println("Library empty: " + books.isEmpty());  // false

        // Practical search pattern
        String searchTitle = "Data Structures";
        if (books.contains(searchTitle)) {
            int index = books.indexOf(searchTitle);
            System.out.println("Found '" + searchTitle + "' at position " + index);
        }
    }
}

These search methods are essential for interactive programs where users are looking for specific items. The pattern of checking contains() before using indexOf() prevents unexpected -1 values.

Common Errors and Debugging

IndexOutOfBoundsException with Methods

This happens when you use an invalid index with methods like get(), set(), or the index version of add() and remove().

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 3

Common causes: Using size() as an index (valid indices are 0 to size()-1), removing elements in loops without adjusting index, assuming empty ArrayLists have valid indices.

Example scenario: You have 3 elements and try to call get(3) - index 3 doesn't exist because indices are 0, 1, 2.

How to fix it: Always check bounds before accessing. Use if (index >= 0 && index < list.size()) to validate indices.

Quick tip: When removing elements in loops, iterate backwards to avoid index shifting issues.

Confusing remove() Overloads

Java can't always tell which remove() method you want, especially with Integer ArrayLists.

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

numbers.remove(1);  // Removes index 1 (value 20), not the number 1!

Common causes: Expecting remove(1) to remove the value 1 from an Integer ArrayList, forgetting that integers can be either indices or values.

How to fix it: For Integer ArrayLists, use remove(Integer.valueOf(1)) to remove the value 1, or remove(0) to remove index 0.

Quick tip: When working with Integer ArrayLists, be extra careful about whether you mean index or value.

Null Pointer Issues

This happens when you try to call methods on ArrayList references that haven't been initialized.

ArrayList<String> list;  // Declared but not initialized
list.add("item");  // NullPointerException!

Common causes: Declaring ArrayList variables without using new, passing null references between methods, forgetting to initialize ArrayLists in constructors.

How to fix it: Always initialize with new ArrayList<Type>() before using. Check for null before calling methods if the ArrayList might not be initialized.

Quick tip: Initialize ArrayLists immediately when you declare them, unless you have a specific reason not to.

Practice Problems

Problem 1: Basic Method Practice

Create an ArrayList of strings representing a to-do list. Add at least 4 tasks, then demonstrate each of these operations:

  • Remove the first task (by index)
  • Remove a specific task by name
  • Replace one task with an updated version
  • Check if a specific task exists
  • Print the final size

Hints: Use different remove() methods, remember that set() replaces elements, and contains() checks existence.

Solution:

import java.util.ArrayList;

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

        // Adding initial tasks
        tasks.add("Study for math test");
        tasks.add("Buy groceries");
        tasks.add("Call doctor");
        tasks.add("Finish essay");

        System.out.println("Original tasks: " + tasks);

        // Remove first task by index
        String completedTask = tasks.remove(0);
        System.out.println("Completed: " + completedTask);

        // Remove specific task by name
        boolean removed = tasks.remove("Buy groceries");
        System.out.println("Successfully removed groceries: " + removed);

        // Replace a task with updated version
        String oldTask = tasks.set(0, "Call doctor to reschedule");
        System.out.println("Updated task (was: " + oldTask + ")");

        // Check if specific task exists
        boolean hasEssay = tasks.contains("Finish essay");
        System.out.println("Still need to finish essay: " + hasEssay);

        // Print final size
        System.out.println("Remaining tasks: " + tasks.size());
        System.out.println("Final list: " + tasks);
    }
}

This demonstrates the practical flow of ArrayList operations in a real-world scenario where tasks are added, completed, and modified.

Problem 2: Grade Management System

Write a method called curveGrades that takes an ArrayList of Integer grades and increases all grades below 70 by 10 points. The method should return how many grades were curved.

Hints: You'll need to loop through indices, use get() to check values, set() to update values, and track changes.

Solution:

import java.util.ArrayList;

public class GradeSystem {
    public static int curveGrades(ArrayList<Integer> grades) {
        int curvedCount = 0;

        for (int i = 0; i < grades.size(); i++) {
            int currentGrade = grades.get(i);
            if (currentGrade < 70) {
                grades.set(i, currentGrade + 10);
                curvedCount++;
            }
        }

        return curvedCount;
    }

    public static void main(String[] args) {
        ArrayList<Integer> testGrades = new ArrayList<Integer>();
        testGrades.add(85);
        testGrades.add(62);
        testGrades.add(78);
        testGrades.add(55);
        testGrades.add(91);

        System.out.println("Original grades: " + testGrades);

        int curved = curveGrades(testGrades);

        System.out.println("After curving: " + testGrades);
        System.out.println("Number of grades curved: " + curved);
    }
}

This problem combines multiple ArrayList methods in a realistic scenario, showing how get(), set(), and size() work together for data processing.

Problem 3: Inventory Management

Create a program that manages a store inventory using an ArrayList of strings. Implement these features:

  • Add new items to inventory
  • Remove items when sold
  • Check if specific items are in stock
  • Find the position of an item
  • Display current inventory size

Hints: You'll use multiple methods per feature - add() for stocking, remove() for sales, contains() for checking stock, indexOf() for position.

Solution:

import java.util.ArrayList;

public class InventorySystem {
    private ArrayList<String> inventory;

    public InventorySystem() {
        inventory = new ArrayList<String>();
    }

    public void addItem(String item) {
        inventory.add(item);
        System.out.println("Added: " + item);
    }

    public boolean sellItem(String item) {
        boolean sold = inventory.remove(item);
        if (sold) {
            System.out.println("Sold: " + item);
        } else {
            System.out.println("Item not in stock: " + item);
        }
        return sold;
    }

    public boolean checkStock(String item) {
        return inventory.contains(item);
    }

    public int findItemPosition(String item) {
        return inventory.indexOf(item);
    }

    public int getInventorySize() {
        return inventory.size();
    }

    public void displayInventory() {
        System.out.println("Current inventory: " + inventory);
    }

    public static void main(String[] args) {
        InventorySystem store = new InventorySystem();

        // Stock some items
        store.addItem("Laptops");
        store.addItem("Phones");
        store.addItem("Tablets");
        store.addItem("Headphones");

        store.displayInventory();

        // Check stock and sell items
        System.out.println("Have phones: " + store.checkStock("Phones"));
        System.out.println("Phones at position: " + store.findItemPosition("Phones"));

        store.sellItem("Phones");
        store.sellItem("Cameras");  // Not in stock

        System.out.println("Inventory size: " + store.getInventorySize());
        store.displayInventory();
    }
}

This comprehensive example shows how ArrayList methods combine to create useful real-world functionality, demonstrating the practical value of mastering the core API.

AP Exam Connections

Multiple Choice Question Patterns

ArrayList method questions on the AP exam focus heavily on understanding return types and the effects of each operation. You'll see questions that ask what happens after a sequence of method calls, or which method call produces a specific result.

Common MCQ patterns include tracing through code that uses multiple ArrayList methods, identifying the correct method to achieve a specific goal, and recognizing when methods will throw exceptions.

Pay special attention to questions about the two versions of remove() - the exam loves testing whether you understand the difference between removing by index vs removing by element.

FRQ Applications

FRQ 3 (Array/ArrayList): This question type directly tests your ability to use ArrayList methods effectively. You might need to implement algorithms that search, filter, or reorganize ArrayList data using the core methods.

Typical scenarios include writing methods that process ArrayLists (using get() and set()), building new ArrayLists from existing data (using add()), or implementing search functionality (using indexOf() and contains()).

FRQ 1 (Methods and Control Structures): ArrayList methods frequently appear as part of larger algorithmic solutions, especially in methods that need to process collections dynamically.

FRQ 2 (Class Design): When designing classes that manage collections of data, you'll use ArrayList methods in constructors, accessor methods, and mutator methods.

Test-Taking Tips

When you see ArrayList method questions, first identify whether the method modifies the list, returns a value, or both. This helps you predict what the code does without getting lost in details.

For questions involving method sequences, work through them step by step, keeping track of both the ArrayList contents and any returned values. The exam often asks about intermediate states, not just final results.

Remember that many ArrayList methods can throw IndexOutOfBoundsException. If you see code with potentially invalid indices, consider whether an exception might occur.

Watch out for questions that mix ArrayList operations with loop structures. These often test your understanding of how list modification affects iteration, especially when removing elements during loops.

Vocabulary

The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.

TermDefinition
add(E obj) methodAn ArrayList method that appends an object to the end of the list and returns true.
add(int index, E obj) methodAn ArrayList method that inserts an object at a specified position and shifts elements to the right.
ArrayListA resizable array implementation in Java that can dynamically grow or shrink to store a collection of objects.
generic typeA parameterized type that specifies the data type of elements a collection will contain, such as ArrayList<E>.
get(int index) methodAn ArrayList method that returns the element at a specified position in the list.
import statementA Java statement used to make classes from a package available for use in a program.
indexA numeric position in a string, starting from 0 for the first character and going up to one less than the length of the string.
java.util packageA Java library package that contains utility classes including ArrayList.
mutableCapable of being changed or modified after creation, such as an ArrayList that can grow or shrink in size.
object referenceA value that points to the memory location where an object is stored, allowing access to that object.
remove(int index) methodAn ArrayList method that removes the element at a specified position and shifts elements to the left.
set(int index, E obj) methodAn ArrayList method that replaces the element at a specified position and returns the former element.
size() methodAn ArrayList method that returns the number of elements currently in the list.
type parameterA placeholder for a specific data type in a generic class, represented by E in ArrayList<E>.