ArrayList Methods
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;
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.
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!
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 1The 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.
See it in action
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.
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:
-
ArrayList<String> chores = new ArrayList<String>();- What's happeningWe create an empty
ArrayListnamedchoresthat will holdStringobjects. - List State
[] - Size0
- What's happening
-
chores.add("Clean room");- What's happeningWe append "Clean room" to the end of the list.
- List State
["Clean room"] - Size1
- What's happening
-
chores.add("Do laundry");andchores.add("Walk the dog");- What's happeningWe append two more items to the end.
- List State
["Clean room", "Do laundry", "Walk the dog"] - Size3
- What's happening
-
chores.add(1, "Finish APUSH reading");- What's happeningWe 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"] - Size4
- What's happening
-
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
setmethod returns the old value, which is stored in thereplacedChorevariable. - List State:
["Deep clean room", "Finish APUSH reading", "Do laundry", "Walk the dog"] - Variable
replacedChore:"Clean room" - Size: 4 (Note:
setdoes not change the size!)
- What's happening: We replace the element at index 0 ("Clean room") with "Deep clean room". The
-
chores.remove(2);- What's happeningWe 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"] - Size3
- What's happening
Final State: The chores list contains ["Deep clean room", "Finish APUSH reading", "Walk the dog"].
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:
-
ArrayList<Integer> points = new ArrayList<Integer>();- What's happeningWe create an empty list to hold
Integerobjects. - List State
[]
- What's happening
-
points.add(2); points.add(3); points.add(2);- What's happeningWe add three scores to the end of the list.
- List State
[2, 3, 2]
- What's happening
-
points.set(0, 1);- What's happeningWe replace the element at index 0 (the first 2) with a 1.
- List State
[1, 3, 2]
- What's happening
-
points.add(1, 1);- What's happeningWe insert a 1 at index 1. The 3 and 2 are shifted to the right.
- List State
[1, 1, 3, 2]
- What's happening
-
int lastScore = points.remove(points.size() - 1);- Why it works: This is a very common pattern.
points.size()is 4. Sopoints.size() - 1is 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 thelastScorevariable. - List State:
[1, 1, 3] - Variable
lastScore:2
- Why it works: This is a very common pattern.
Final State: The points list is [1, 1, 3] and the lastScore variable holds the integer 2.
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?
Practice — 8 questions
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.
import java.util.ArrayList;
- 4.8.A: Develop code for collections of related objects using ArrayList objects and determine the result of calling methods on these objects.
- 4.8.A.1
- An ArrayList object is mutable in size and contains object references.
- 4.8.A.2
- The ArrayList constructor ArrayList() constructs an empty list.
- 4.8.A.3
- Java allows the generic type ArrayList<E>, where the type parameter E specifies the type of the elements. When ArrayList<E> is specified, the types of the reference parameters and return type when using the ArrayList methods are type E. ArrayList<E> is preferred over ArrayList. For example, ArrayList<String> names = new ArrayList<String>(); allows the compiler to find errors that would otherwise be found at run-time.
- 4.8.A.4
- The ArrayList class is part of the java.util package. An import statement must be used to make this class available for use in the program.
- 4.8.A.5
- The following ArrayList methods— including what they do and when they are used—are part of the Java Quick Reference: • int size() returns the number of elements in the list. • boolean add(E obj) appends obj to end of list; returns true. • void add(int index, E obj) inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size. • E get(int index) returns the element at position index in the list. • E set(int index, E obj) replaces the element at position index with obj; returns the element formerly at position index. • E remove(int index) removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index.
- 4.8.A.6
- The indices for an ArrayList start at 0 and end at the number of elements - 1.
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;
Read what Saavi narrates
Hello there, it's Saavi. Let's talk about one of the most flexible tools you'll use in Java.
Imagine you're planning a party for your friend, Maya. You start a guest list. At first, it's just a few people. But then, Carlos can make it, so you add him. Priya has to cancel, so you take her off the list. You need a list that can change... one that grows and shrinks.
That's exactly what an ArrayList is. Unlike a regular array that's a fixed size, an ArrayList is a dynamic collection that can change as your program runs. We use a set of built-in commands, called methods, to manage it.
Let's look at an example. Imagine Aaliyah is using an ArrayList to manage her weekend chores.
First, she creates an empty list called chores.
Then, she adds "Clean room", then "Do laundry", then "Walk the dog".
Her list now has three items.
Next, she uses the add method again, but this time with an index. She wants to insert "Finish APUSH reading" at index one. So, "Do laundry" and "Walk the dog" have to shuffle back to make space. Her list now has four items, with the reading assignment as the second item.
Then, she decides to replace "Clean room" with "Deep clean room". She uses the set method at index zero. The list size doesn't change, but the first item is updated.
Finally, she removes the item at index two, which is now "Do laundry". The list shrinks, and "Walk the dog" slides over to fill the empty spot.
The final list of chores is "Deep clean room", "Finish APUSH reading", and "Walk the dog".
See how we used add, set, and remove to manage the list? One of the most common mistakes students make is forgetting that when you remove an item, the indices of everything after it change. After Aaliyah removed "Do laundry" from index two, "Walk the dog", which was at index three, is now at index two. If you're not careful, this can cause tricky bugs in your code.
Keep practicing with these methods. You'll find they are incredibly powerful, and you'll be using them all the time. You've got this.
`ArrayList` is an object, not a basic array. It doesn't support the `[]` syntax.
Use the `get()` method: `myList.get(0)`.
If you remove an item from the middle of the list, everything after it shifts to the left. If your code doesn't account for this (e.g., in a loop), you might skip an element or go out of bounds.
After a `remove(i)`, remember that the element that was at `i+1` is now at index `i`.
`add` inserts a new element and increases the list size. `set` replaces an existing element and the size stays the same. Using the wrong one will lead to a list with an incorrect size and contents.
Think: "Am I *adding* a new chair to the row (and shifting people down), or am I asking someone to leave and *setting* a new person in their place?"
If a list has 5 elements, its size is 5, but its valid indices are 0, 1, 2, 3, and 4. Index 5 does not exist. This will cause an `IndexOutOfBoundsException`.
Always remember the valid index range is `0` to `list.size() - 1`.
The compiler won't know what an `ArrayList` is, and your code won't even start to compile.
Make it a habit. The moment you type `ArrayList`, go to the top of your file and add the import statement.
This creates a "raw" list that can hold any type of object. You lose the compiler's help in preventing type errors, so you could accidentally add an `Integer` to a list of `String`s and not find out until your program crashes.
Always specify the type: `ArrayList<String> names = new ArrayList<String>();`.