Fiveable
Fiveable
crams
AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

7.2 ArrayList Methods

Verified for the 2025 AP Computer Science A examCitation:

Once you have an ArrayList, the real power comes from the many methods that allow you to manipulate the data it contains. In this guide, we'll explore the essential ArrayList methods that let you examine, add, remove, and modify elements in your dynamic collections.

Importing ArrayList

Before using ArrayList, remember to import it:

import java.util.ArrayList;

The ArrayList class is part of the java.util package. This import statement makes the class available for use in your program.

Essential ArrayList Methods

Let's explore the core methods that are part of the Java Quick Reference and will be available to you on the AP Exam. These methods include get(int index) for retrieving elements, add with parameters like int index, E obj for inserting elements at specific positions, and remove(int index) for deleting elements from specific positions.

Finding the Size of an ArrayList

The size() method returns the number of elements currently in the list:

// Create an ArrayList with some elements
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Get the size
int count = fruits.size();
System.out.println("Number of fruits: " + count);  // Outputs: Number of fruits: 3

Adding Elements

There are two versions of the add method:

1. Adding to the End

The add(E obj) method appends an element to the end of the list:

ArrayList<String> names = new ArrayList<String>();
names.add("Alex");    // List is now ["Alex"]
names.add("Blake");   // List is now ["Alex", "Blake"]
names.add("Casey");   // List is now ["Alex", "Blake", "Casey"]

// The add method returns true if successful
boolean success = names.add("Dana");  // returns true

2. Adding at a Specific Position

The add(int index, E obj) method inserts an element at a specific position. The parameter int index specifies where to insert the element, and E obj represents the element to be inserted:

ArrayList<String> animals = new ArrayList<String>();
animals.add("Dog");    // List is now ["Dog"]
animals.add("Cat");    // List is now ["Dog", "Cat"]

// Insert "Bird" at index 1
animals.add(1, "Bird"); // List is now ["Dog", "Bird", "Cat"]

// When you add at a specific index:
// 1. Elements at that index and higher move right
// 2. The size increases by 1

Important notes about add(int index, E obj):

  • The valid range for index is from 0 to size() (inclusive)
  • If index equals size(), the element is added to the end
  • If index is out of range, an IndexOutOfBoundsException is thrown
  • The method has a void return type (doesn't return anything)

Accessing Elements

The get(int index) method returns the element at the specified position:

ArrayList<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");

// Get the element at index 1
String color = colors.get(1);
System.out.println(color);  // Outputs: Green

Important notes:

  • Valid indices are from 0 to size()-1
  • If the index is out of range, an IndexOutOfBoundsException is thrown
  • The return type is the generic type E of the ArrayList

Modifying Elements

The set(int index, E obj) method replaces the element at a specific position:

ArrayList<String> planets = new ArrayList<String>();
planets.add("Mercury");
planets.add("Venus");
planets.add("Earf");  // Oops, a typo!

// Replace "Earf" with "Earth"
String oldValue = planets.set(2, "Earth");
System.out.println("Replaced: " + oldValue);  // Outputs: Replaced: Earf

Important notes:

  • The method returns the element that was replaced
  • The size of the ArrayList doesn't change
  • Valid indices are from 0 to size()-1
  • If the index is out of range, an IndexOutOfBoundsException is thrown

Removing Elements

The remove(int index) method removes the element at the specified position:

ArrayList<String> foods = new ArrayList<String>();
foods.add("Pizza");
foods.add("Burger");
foods.add("Sushi");
foods.add("Salad");

// Remove the element at index 1
String removed = foods.remove(1);
System.out.println("Removed: " + removed);  // Outputs: Removed: Burger
System.out.println(foods);  // Outputs: [Pizza, Sushi, Salad]

Important notes about remove(int index):

  • Elements at positions higher than index move left
  • The size of the ArrayList decreases by 1
  • The method returns the element that was removed
  • Valid indices are from 0 to size()-1
  • If the index is out of range, an IndexOutOfBoundsException is thrown

Visual Example: How Methods Affect an ArrayList

Let's trace through a sequence of operations:

ArrayList<String> items = new ArrayList<String>();
items.add("A");       // items = ["A"]
items.add("B");       // items = ["A", "B"]
items.add("C");       // items = ["A", "B", "C"]
items.add(1, "D");    // items = ["A", "D", "B", "C"]
items.set(2, "E");    // items = ["A", "D", "E", "C"]
items.remove(0);      // items = ["D", "E", "C"]

Common ArrayList Patterns

Traversing an ArrayList

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

// Using an indexed for loop
for (int i = 0; i < numbers.size(); i++) {
    System.out.println("Element at " + i + ": " + numbers.get(i));
}

// Using an enhanced for loop
for (Integer num : numbers) {
    System.out.println("Value: " + num);
}

Modifying All Elements

ArrayList<Integer> values = new ArrayList<Integer>();
values.add(5);
values.add(10);
values.add(15);

// Double each value
for (int i = 0; i < values.size(); i++) {
    values.set(i, values.get(i) * 2);
}
// values is now [10, 20, 30]

Finding and Removing an Element

ArrayList<String> names = new ArrayList<String>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

// Find and remove "Bob"
for (int i = 0; i < names.size(); i++) {
    if (names.get(i).equals("Bob")) {
        names.remove(i);
        break;  // Exit the loop after removing
    }
}
// names is now ["Alice", "Charlie"]

Important Considerations

Avoiding Common Errors

  1. Out of Bounds Access: Always ensure index values are within the valid range (0 to size()-1).

  2. Modifying While Traversing: Be careful when removing elements during a for loop:

    // INCORRECT: This can cause problems
    for (int i = 0; i < list.size(); i++) {
        if (someCondition(list.get(i))) {
            list.remove(i);
            // Problem: After removing, elements shift left,
            // but i still increases, potentially skipping elements
        }
    }
    
    // BETTER: Traverse backwards
    for (int i = list.size() - 1; i >= 0; i--) {
        if (someCondition(list.get(i))) {
            list.remove(i);
        }
    }
    
  3. Wrapper Classes vs. Primitives: Remember that ArrayList stores objects, not primitives:

    // This works due to autoboxing
    ArrayList<Integer> nums = new ArrayList<Integer>();
    nums.add(42);  // Java converts int to Integer
    
    // But be careful with equality
    Integer a = 128;
    Integer b = 128;
    System.out.println(a == b);      // Might print false (object reference comparison)
    System.out.println(a.equals(b)); // Prints true (value comparison)
    

Summary

ArrayList methods provide powerful tools for managing dynamic collections. The key methods—size(), add(E), add(int, E), get(int), set(int, E), and remove(int)—allow you to examine, modify, and manipulate elements in your list. Understanding how these methods work and their effects on the structure of the ArrayList is crucial for effective Java programming. Remember to be careful with index values and to consider how operations like adding and removing affect the positions of other elements in the list.

Key Terms to Review (4)

ArrayList: ArrayList is a dynamic data structure that allows you to store and manipulate collections of objects. Unlike arrays, ArrayLists can grow or shrink dynamically as needed.
Get(int index): The method get(int index) is used to retrieve the element at a specific index in an array or list.
Remove(int index): The method remove(int index) is used to delete an element from a list at a specific index position.
Set(int index, E obj): The method set(int index, E obj) is used to replace an element in a list at a specific index position with a new element.