Getting Started
In programming, we often need to manage collections of data whose size can change during program execution. While arrays are excellent for fixed-size lists, they cannot grow or shrink. To solve this, Java provides the ArrayList class, a powerful and flexible tool for storing and manipulating an ordered collection of objects that can dynamically resize itself as needed.
What You Should Be Able to Do
Determine the number of elements currently stored in an
ArrayList.Access an element at a specific position (index) within an
ArrayList.Modify an element at a specific position in an
ArrayList.Add a new element to the end of an
ArrayList.Insert a new element at a specific position in an
ArrayList, shifting subsequent elements.Remove an element from a specific position in an
ArrayList, shifting subsequent elements.
Key Concepts & Java Implementation
The Core Idea
An ArrayList is an object that represents a resizable list of other objects. Think of it as a "smart" array that automatically handles the work of growing and shrinking. Like an array, an ArrayList maintains the order of its elements and uses zero-based indexing to identify each element's position. The first element is at index 0, the second at index 1, and so on.
The power of ArrayList comes from its built-in methods. A method is a named block of code that belongs to an object and performs a specific action. Instead of manually managing an array's size, we can simply call methods like .add() or .remove() on an ArrayList object, and it will adjust its internal structure accordingly. This makes managing dynamic collections of data significantly simpler and less error-prone.
Syntax & Implementation
The ArrayList class provides several essential methods for manipulation. To use them, you must first have an ArrayList object.
// This line creates an empty ArrayList that can hold String objects.
ArrayList<String> guestList = new ArrayList<String>();
The most common ArrayList methods are summarized below. Note that E is a placeholder for the type of element the ArrayList holds (e.g., String, Integer).
| Method Signature | Purpose | Return Value |
|---|---|---|
int size() | Returns the number of elements in the list. | An int |
E get(int index) | Returns the element at the specified index. | The element of type E |
E set(int index, E obj) | Replaces the element at the index with obj. | The original element that was replaced |
boolean add(E obj) | Appends the specified element to the end of the list. | true (always) |
void add(int index, E obj) | Inserts the element obj at the specified index. | (none) |
E remove(int index) | Removes the element at the specified index. | The element that was removed |
Annotated Java Examples
Example 1: Adding and Sizing
This example demonstrates creating a list, adding elements to the end, and checking its size.
import java.util.ArrayList; // Required to use the ArrayList class
public class PlaylistManager {
public static void main(String[] args) {
// Create an ArrayList to store song titles
ArrayList<String> playlist = new ArrayList<String>();
// Use the add(E obj) method to append elements to the end
playlist.add("Bohemian Rhapsody");
playlist.add("Stairway to Heaven");
playlist.add("Hotel California");
// Use the size() method to get the number of elements
System.out.println("Number of songs: " + playlist.size()); // Output: Number of songs: 3
}
}
Example 2: Accessing and Modifying
This example shows how to retrieve an element with get() and replace an element with set().
import java.util.ArrayList;
public class Gradebook {
public static void main(String[] args) {
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(88);
scores.add(92);
scores.add(77);
// Use get(index) to access the element at index 1 (the second element)
int secondScore = scores.get(1);
System.out.println("Second score: " + secondScore); // Output: Second score: 92
// Use set(index, E obj) to change the element at index 0
// The set method returns the old value that was replaced.
int oldScore = scores.set(0, 90);
System.out.println("Updated first score. The old score was: " + oldScore); // Output: 88
System.out.println("Current scores: " + scores); // Output: Current scores: [90, 92, 77]
}
}
Tracing & Analysis
The most important behavior to understand is how add(index, obj) and remove(index) affect the list. Both methods shift all subsequent elements.
Execution Trace
Let's trace the state of an ArrayList named items through a series of operations.
| Java Code Executed | items State (Elements and Indices) | items.size() | Comment |
|---|---|---|---|
items.add("A"); | ["A"] (index 0) | 1 | "A" is added to the end. |
items.add("B"); | ["A", "B"] (indices 0, 1) | 2 | "B" is added to the end. |
items.add("C"); | ["A", "B", "C"] (indices 0, 1, 2) | 3 | "C" is added to the end. |
items.add(1, "X"); | ["A", "X", "B", "C"] (indices 0, 1, 2, 3) | 4 | "X" is inserted at index 1. "B" and "C" are shifted right. |
items.remove(2); | ["A", "X", "C"] (indices 0, 1, 2) | 3 | The element at index 2 ("B") is removed. "C" is shifted left. |
Analysis
When you use an index in an ArrayList method, you must provide a valid index.
For
get,set, andremove, the valid indices are from0tosize() - 1.For
add(index, obj), the valid indices are from0tosize(). Usingsize()as the index is equivalent to adding the element to the end.
Attempting to use an index outside this valid range will cause a runtime error called an IndexOutOfBoundsException. This is a very common error, so always be mindful of the list's current size when working with indices.
Java Syntax Quick-Reference
A summary of the core ArrayList methods covered in this topic. Assume list is an ArrayList of type E.
list.size(): Returns the number of elements inlistas anint.list.get(index): Returns the element at the specifiedindex.list.set(index, newValue): Replaces the element atindexwithnewValueand returns the original element.list.add(newValue): AppendsnewValueto the end of the list.list.add(index, newValue): InsertsnewValueatindex, shifting subsequent elements to the right.list.remove(index): Removes the element atindex, shifting subsequent elements to the left, and returns the removed element.
Core Code Examples & Terminology
ArrayList: A class from the Java library that implements a resizable list of objects, providing methods for dynamic manipulation.Index: An integer that specifies an element's position in an
ArrayList, starting from 0 for the first element.IndexOutOfBoundsException: A runtime error thrown when a program attempts to access a list with an index that is negative or is greater than or equal to the list's size.Method: A procedure associated with an object that performs a task. We invoke methods using dot notation (e.g.,
myList.size()).Parameter: A value passed into a method to specify its behavior. For example, in
list.get(0), the0is a parameter.Return Value: The value that a method gives back after it finishes its execution. For example,
list.size()returns an integer.Core Snippet 1: Creating and Populating an
ArrayListArrayList<String> words = new ArrayList<String>(); words.add("Hello"); words.add("World");This code creates an empty list for
Stringobjects and adds two elements to its end.Core Snippet 2: Accessing and Modifying an Element
String firstWord = words.get(0); // Gets "Hello" words.set(1, "Java"); // Replaces "World" with "Java"This code retrieves the first element and then changes the second element in the list.
Core Snippet 3: Inserting and Removing an Element
words.add(0, "First"); // Inserts "First" at the beginning String removedWord = words.remove(1); // Removes "Hello"This code inserts an element at a specific index and then removes an element, shifting others.
Core Skill Check
Code Tracing: What is printed by the last line of this Java code?
ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(10); nums.add(20); nums.add(30); nums.set(1, 5); nums.add(1, 15); nums.remove(2); System.out.println(nums.get(1));Debugging: Identify the runtime error in this Java code.
ArrayList<String> names = new ArrayList<String>(); names.add("Alice"); names.add("Bob"); System.out.println(names.get(2));Application: Write a single line of Java code that removes the first element from an
ArrayListnamedshoppingList.
Common Misconceptions & Errors
Forgetting Zero-Based Indexing: The first element is always at index
0, not1. The last element is at indexsize() - 1.Accessing an Index Equal to
size(): Trying toget,set, orremovean element at indexlist.size()will cause anIndexOutOfBoundsException. This index does not exist; it is one position past the end of the list.Ignoring the Shift: Forgetting that
add(index, element)andremove(index)change the indices of all elements that come after the specified index. This can lead to logic errors in loops that modify the list they are iterating over.Confusing
setandadd: Thesetmethod replaces an existing element. Theaddmethod inserts a new element and increases the list's size.
Summary
The ArrayList is a fundamental data structure in Java for managing dynamic collections of objects. It provides a suite of methods that simplify common list operations. The size() method reports the number of elements, while get(index) and set(index, value) allow for direct access and modification of elements using their zero-based index. The add(value) method appends to the end, whereas add(index, value) and remove(index) insert or delete elements at specific positions, automatically shifting other elements to accommodate the change. Mastering these methods is key to effectively manipulating collections of data whose size is not known in advance.