
Arrays have a fixed size. Once you create an array of 10 elements, it stays at 10. If you need 11, you’re stuck. ArrayList solves this problem. It grows and shrinks automatically as you add and remove elements.
ArrayList is part of Java’s Collections Framework, a set of classes for storing and manipulating groups of objects. It’s one of the most commonly used classes in Java.
Creating an ArrayList
First, import the class:
import java.util.ArrayList;
Then create an ArrayList by specifying the type of elements it will hold:
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
ArrayList<Double> prices = new ArrayList<Double>();
The type in angle brackets is called a generic type parameter. It tells Java what kind of objects the list will contain.
You can shorten the right side since Java can infer the type:
ArrayList<String> names = new ArrayList<>();
Wrapper Classes
ArrayList stores objects, not primitives. You can’t create an ArrayList<int>. Instead, use the wrapper class:
- int → Integer
- double → Double
- boolean → Boolean
- char → Character
- long → Long
- float → Float
Java automatically converts between primitives and wrapper classes (called autoboxing and unboxing):
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5); // int 5 is autoboxed to Integer
int value = numbers.get(0); // Integer is unboxed to int
Adding Elements
The add() method appends an element to the end:
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println(fruits); // [Apple, Banana, Cherry]
Add at a specific position with add(index, element):
fruits.add(1, "Blueberry"); // Insert at index 1
System.out.println(fruits); // [Apple, Blueberry, Banana, Cherry]
Existing elements shift to make room. Unlike arrays, this doesn’t overwrite anything.
Accessing Elements
Use get(index) to retrieve an element:
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println(colors.get(0)); // Red
System.out.println(colors.get(2)); // Blue
Indices start at 0, just like arrays. Accessing an invalid index throws IndexOutOfBoundsException.
Modifying Elements
The set(index, element) method replaces an element at a specific position:
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.set(1, "Yellow"); // Replace index 1
System.out.println(colors); // [Red, Yellow, Blue]
Removing Elements
Remove by index:
ArrayList<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.remove(1); // Remove element at index 1
System.out.println(items); // [A, C]
Remove by value:
items.remove("A"); // Remove first occurrence of "A"
System.out.println(items); // [C]
When removing by value, remove() returns true if the element was found and removed, false otherwise.
Clear all elements:
items.clear();
System.out.println(items); // []
Size and Empty Check
The size() method returns the number of elements:
ArrayList<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);
nums.add(30);
System.out.println(nums.size()); // 3
Check if empty with isEmpty():
ArrayList<String> list = new ArrayList<>();
System.out.println(list.isEmpty()); // true
list.add("item");
System.out.println(list.isEmpty()); // false
Searching
Check if an element exists with contains():
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.contains("Bob")); // true
System.out.println(names.contains("Diana")); // false
Find the position with indexOf():
int position = names.indexOf("Charlie"); // 2
int notFound = names.indexOf("Diana"); // -1
The method returns -1 if the element isn’t found.
Looping Through ArrayList
Enhanced for Loop
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
for (String color : colors) {
System.out.println(color);
}
This is the cleanest way when you don’t need the index.
Traditional for Loop
for (int i = 0; i < colors.size(); i++) {
System.out.println(i + ": " + colors.get(i));
}
Use this when you need the index or plan to modify the list during iteration.
forEach Method
colors.forEach(color -> System.out.println(color));
This uses a lambda expression. We’ll cover lambdas in a later tutorial.
ArrayList vs Array
When should you use each?
Use arrays when:
- Size is fixed and known
- You need primitives without wrapper overhead
- Performance is critical (arrays are slightly faster)
- Working with multidimensional data
Use ArrayList when:
- Size changes during execution
- You need to add or remove elements
- You want convenient methods like contains() and indexOf()
- Flexibility matters more than raw performance
For most situations, ArrayList is the better default choice. Use arrays when you have a specific reason.
Converting Between Arrays and ArrayList
Array to ArrayList
import java.util.ArrayList;
import java.util.Arrays;
String[] array = {"A", "B", "C"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
System.out.println(list); // [A, B, C]
ArrayList to Array
ArrayList<String> list = new ArrayList<>();
list.add("X");
list.add("Y");
list.add("Z");
String[] array = list.toArray(new String[0]);
System.out.println(Arrays.toString(array)); // [X, Y, Z]
The new String[0] argument tells Java what type of array to create.
Sorting
Use Collections.sort() to sort an ArrayList:
import java.util.ArrayList;
import java.util.Collections;
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 8]
For reverse order:
Collections.sort(numbers, Collections.reverseOrder());
System.out.println(numbers); // [8, 5, 2, 1]
Strings sort alphabetically:
ArrayList<String> names = new ArrayList<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
Collections.sort(names);
System.out.println(names); // [Alice, Bob, Charlie]
Practical Example: Shopping Cart
Here’s a shopping cart that demonstrates ArrayList operations:
import java.util.ArrayList;
import java.util.Scanner;
public class ShoppingCart {
public static void main(String[] args) {
ArrayList<String> cart = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n--- Shopping Cart ---");
System.out.println("1. Add item");
System.out.println("2. Remove item");
System.out.println("3. View cart");
System.out.println("4. Check for item");
System.out.println("5. Clear cart");
System.out.println("6. Exit");
System.out.print("Choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Item to add: ");
String itemToAdd = scanner.nextLine();
cart.add(itemToAdd);
System.out.println(itemToAdd + " added.");
break;
case 2:
if (cart.isEmpty()) {
System.out.println("Cart is empty.");
} else {
System.out.print("Item to remove: ");
String itemToRemove = scanner.nextLine();
if (cart.remove(itemToRemove)) {
System.out.println(itemToRemove + " removed.");
} else {
System.out.println("Item not found.");
}
}
break;
case 3:
if (cart.isEmpty()) {
System.out.println("Cart is empty.");
} else {
System.out.println("Items in cart:");
for (int i = 0; i < cart.size(); i++) {
System.out.println((i + 1) + ". " + cart.get(i));
}
System.out.println("Total items: " + cart.size());
}
break;
case 4:
System.out.print("Item to check: ");
String itemToCheck = scanner.nextLine();
if (cart.contains(itemToCheck)) {
int index = cart.indexOf(itemToCheck);
System.out.println(itemToCheck + " is in cart at position " + (index + 1));
} else {
System.out.println(itemToCheck + " is not in cart.");
}
break;
case 5:
cart.clear();
System.out.println("Cart cleared.");
break;
case 6:
System.out.println("Goodbye!");
scanner.close();
return;
default:
System.out.println("Invalid choice.");
}
}
}
}
Removing While Iterating
Removing elements while looping through an ArrayList requires care. The enhanced for loop throws ConcurrentModificationException if you modify the list during iteration.
// This crashes
for (String item : items) {
if (item.startsWith("A")) {
items.remove(item); // ConcurrentModificationException
}
}
Solutions:
Loop backward with traditional for:
for (int i = items.size() - 1; i >= 0; i--) {
if (items.get(i).startsWith("A")) {
items.remove(i);
}
}
Use removeIf (Java 8+):
items.removeIf(item -> item.startsWith("A"));
The removeIf() method is cleaner and handles the iteration safely.
Common Mistakes
Using == instead of equals() for contains/indexOf. These methods use equals() internally, so they work correctly. But if you search manually, remember to use equals() for object comparison.
Modifying during enhanced for loop. Use a traditional loop, loop backward, or use removeIf().
Forgetting wrapper classes. Use Integer instead of int, Double instead of double.
Index out of bounds. Valid indices are 0 to size()-1, just like arrays.
Confusing size() with capacity. An ArrayList can have internal capacity for 100 elements but contain only 3. The size() method returns how many elements are actually stored.
What’s Next
You now have the tools to write substantial programs: methods for organization, arrays for fixed collections, and ArrayList for dynamic ones. The next phase introduces object-oriented programming, where you’ll learn to create your own custom types with classes and objects.
Related: Java Arrays Explained | Introduction to Object-Oriented Programming
Sources
- Oracle. “ArrayList (Java SE 21).” Java Documentation. docs.oracle.com
- Oracle. “The List Interface.” The Java Tutorials. docs.oracle.com


