Java Collections Framework
When you have a large number of objects of the same or different types that you want to store and retrieve in memory, you need a way to structure and manage them. In Computer Science, you learn about the term Data Structures, which precisely help you organize, modify, and retrieve a large collection of data.
In Java, the Collections Framework provides us with many types of Data Structures, each having its specific advantages over the others. The choice of which data structure to use depends upon your application and what you are trying to accomplish. In this section, we will learn about the ArrayList.
Unit 4.8: ArrayList Methods
The ArrayList Class
An ArrayList object is mutable in size and contains object references. Unlike standard arrays, which have a fixed capacity, an ArrayList can grow as you add elements and shrink as you remove them.
ArrayListobjects manage their own internal storage. They automatically expand when elements are added and contract when elements are removed, providing more flexibility than fixed-size arrays.
Task: Comparing standard array syntax with ArrayList mutation.
// Standard array (Fixed size)
String[] arr = new String[3];
// ArrayList (Mutable size)
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D"); // Grows to size 4 automatically
Important Note: An ArrayList cannot store primitive values (like int or double) directly. It can only store objects.
Task: Identifying correct usage of generic types with wrapper classes.
// INCORRECT: Cannot use primitives in the declaration
// ArrayList<int> list = new ArrayList<int>(); // COMPILER ERROR
// CORRECT: Must use Wrapper classes
ArrayList<Integer> list2 = new ArrayList<Integer>();
Package and Import
The ArrayList class is part of the java.util package. An import statement must be used to make this class available in your program.
Task: Importing and using the ArrayList class.
import java.util.ArrayList; // Required to use ArrayList
public class MyClass
{
ArrayList<Integer> scores;
}
Creation and Generics
Java allows the generic type ArrayList<E>, where the type parameter E specifies the type of the elements. Using generics allows the compiler to find errors that would otherwise be found at run-time.
- Generics ensure that only the specified type of object can be stored in the list. This "type-checking" happens at compile-time, preventing many bugs before the program even runs.
- Syntax:
ArrayList<Type> list = new ArrayList<Type>(); - Reference Types Only: The type
Emust be a Reference type (likeString,Integer, orDouble). You cannot use primitives (likeintordouble) directly.
Task: Creating ArrayList objects with specific reference types.
// Correct: Reference types
ArrayList<String> sList = new ArrayList<String>();
ArrayList<Double> dList = new ArrayList<Double>();
// Incorrect: Primitive types (Compiler Error)
// ArrayList<int> bad1 = new ArrayList<int>();
// ArrayList<double> bad2 = new ArrayList<double>();
The Constructor
The ArrayList class provides multiple constructors:
ArrayList(): Constructs an empty list with an initial size of 0.ArrayList(int initialCapacity): Constructs an empty list but pre-allocates enough space to hold the specified number of elements. This is used for efficiency when you already know approximately how many items you will be adding.
Capacityis the number of elements the internal storage can hold without resizing.Sizeis the number of elements actually present in the list.
Important Note: Even when you provide an initial capacity, the size() of the list is still 0 until you actually add elements.
Task: Pre-allocating capacity versus checking actual size.
// Pre-allocate space for 100 items
ArrayList<Integer> nums = new ArrayList<Integer>(100);
System.out.println(nums.size()); // Still prints 0!
Essential Methods
The following methods are part of the Java Quick Reference provided during the AP Exam.
| Method | Description | Return Type |
|---|---|---|
int size() |
Returns the number of elements in the list. | int |
boolean add(E obj) |
Appends obj to the end of the list; always returns true. |
boolean |
void add(int i, E obj) |
Inserts obj at index i. Elements at i and higher are shifted right. |
void |
E get(int i) |
Returns the element at index i. |
E |
E set(int i, E obj) |
Replaces the element at i with obj. Returns the old value. |
E |
E remove(int i) |
Removes element at i. Elements to the right are shifted left. Returns the removed value. |
E |
1. Appending vs. Inserting
Task: Appending elements to the end versus inserting at a specific index.
ArrayList<String> list = new ArrayList<String>();
list.add("First"); // Appends to the END. Size is now 1.
list.add("Last"); // Appends to the END. Size is now 2.
list.add(1, "Middle"); // Inserts at index 1.
// result: ["First", "Middle", "Last"]
2. Replacing and Removing (The Return Values)
Both set and remove return the value that was previously at that position.
Task: Capturing return values from set and remove operations.
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
// set returns the OLD value
String oldVal = list.set(0, "Apricot"); // oldVal is "Apple"
// remove returns the DELETED value
String deleted = list.remove(1); // deleted is "Banana"
3. Getting and Size
Task: Retrieving elements and checking list size.
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
int count = list.size(); // count is 2
String letter = list.get(0); // letter is "A"
Insertion Shifting Example
When you insert an element, every subsequent element must move to the right to make room.
Task: Visualizing index shifts during insertion.
ArrayList<String> letters = new ArrayList<String>();
letters.add("A");
letters.add("C");
// Insert "B" at index 1
letters.add(1, "B");
// "C" was shifted from index 1 to index 2
// List is now: ["A", "B", "C"]
Removal Shifting Example
When you remove an element, every subsequent element moves to the left to fill the gap.
Task: Visualizing index shifts during removal.
ArrayList<String> list = new ArrayList<String>();
list.add("Red");
list.add("Green");
list.add("Blue");
String gone = list.remove(0); // Removes "Red"
// "Green" moves from index 1 to 0
// "Blue" moves from index 2 to 1
// gone is "Red", list size is now 2
Indices and Bounds
- The indices for an
ArrayListstart at0and end atsize() - 1. - The Exception: Attempting to access an index outside of this range (e.g.,
list.get(10)when size is 5) will result in anIndexOutOfBoundsException.
Task: Accessing valid and invalid indices.
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(100);
System.out.println(nums.get(0)); // Valid
// System.out.println(nums.get(1)); // ERROR: IndexOutOfBoundsException
Examples
Complete ArrayList Operations
Task: Performing a sequence of standard ArrayList operations.
import java.util.ArrayList;
public class ListExample
{
public static void main(String[] args)
{
// Create an empty list of Strings
ArrayList<String> names = new ArrayList<String>();
names.add("Alice"); // ["Alice"]
names.add("Bob"); // ["Alice", "Bob"]
// Insert "Charlie" at index 1
names.add(1, "Charlie"); // ["Alice", "Charlie", "Bob"]
// Replace "Alice" with "Ann"
String oldName = names.set(0, "Ann"); // ["Ann", "Charlie", "Bob"]
// Remove "Charlie"
String removed = names.remove(1); // ["Ann", "Bob"]
System.out.println("Current List: " + names);
System.out.println("Size: " + names.size());
System.out.println("Old name at 0 was: " + oldName);
System.out.println("Removed name was: " + removed);
}
}

Points to Note:
- The indices for an
ArrayListstart at0and go up tosize() - 1. - It is typical to use the enhanced for loop (for-each) to iterate through collections.
- Lists accept duplicate values without any issues.
- The
ArrayList<E>syntax is preferred over the rawArrayListsyntax because it provides type safety.
Excluded from AP CSA Exam
- Internal Implementation: Technical details regarding how
ArrayListis implemented (e.g., as a wrapper around a basic array that resizes) are outside the scope of the course.
- The
ListInterface: In professional development, it is customary to declare variables using theListinterface (e.g.,List<String> list = new ArrayList<>();). However, the AP Exam focuses specifically on theArrayListclass.
- Polymorphism: While
ArrayListimplements theListinterface, interfaces and polymorphic declarations are not tested in the context of Unit 4.