Java ArrayList
Learn how to work with dynamic, resizable arrays in Java using the ArrayList class from the Collections Framework.
What is ArrayList?
ArrayList is a resizable array implementation in Java that belongs to the java.util package. Unlike regular arrays that have a fixed size, ArrayList can grow and shrink automatically as you add or remove elements.
Think of it like a backpack that expands when you put more items in it and shrinks when you take items out!
- Dynamic Size: Automatically adjusts its size when elements are added or removed
- Indexed Access: Access elements quickly using index positions (just like arrays)
- Flexible Operations: Easy insertion, deletion, and searching of elements
- Type Safety: Use generics to ensure type-safe operations
๐ก Key Point: ArrayList maintains the order of insertion, meaning elements stay in the sequence you added them.
Creating and Using ArrayList
Here's how to create an ArrayList and perform basic operations:
Example: ArrayList Basic Operations
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList fruits = new ArrayList<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
// Display ArrayList
System.out.println("Fruits: " + fruits);
// Accessing an element
System.out.println("First fruit: " + fruits.get(0));
// Changing an element
fruits.set(1, "Grapes");
System.out.println("After change: " + fruits);
// Removing an element
fruits.remove("Orange");
System.out.println("After removal: " + fruits);
// Size of ArrayList
System.out.println("Total fruits: " + fruits.size());
}
}
Fruits: [Apple, Banana, Orange, Mango] First fruit: Apple After change: [Apple, Grapes, Orange, Mango] After removal: [Apple, Grapes, Mango] Total fruits: 3
Explanation:
ArrayList<String>- Creates an ArrayList that stores String objects onlyadd()- Adds elements to the end of the listget(index)- Retrieves the element at the specified positionset(index, element)- Replaces the element at the specified positionremove()- Removes the specified element or element at indexsize()- Returns the number of elements in the list
Common ArrayList Methods
1. Adding Elements
You can add elements at the end or at a specific position in the ArrayList.
Methods: add(element), add(index, element), addAll(collection)
2. Accessing Elements
Retrieve elements using their index position or check if an element exists.
Methods: get(index), contains(element), indexOf(element)
3. Modifying Elements
Update existing elements or remove them from the list.
Methods: set(index, element), remove(element), remove(index), clear()
4. Checking and Iterating
Check the size, if empty, or loop through all elements.
Methods: size(), isEmpty(), for-each loop, iterator()
Looping Through ArrayList
There are multiple ways to iterate through an ArrayList. Here are the most common methods:
Example: Different Ways to Loop
import java.util.ArrayList;
public class LoopExample {
public static void main(String[] args) {
ArrayList numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
// Method 1: For-each loop (Most common)
System.out.println("Using for-each loop:");
for (Integer num : numbers) {
System.out.println(num);
}
// Method 2: Traditional for loop
System.out.println("\nUsing traditional for loop:");
for (int i = 0; i < numbers.size(); i++) {
System.out.println(numbers.get(i));
}
// Method 3: forEach with Lambda (Java 8+)
System.out.println("\nUsing forEach method:");
numbers.forEach(num -> System.out.println(num));
}
}
Using for-each loop: 10 20 30 40 Using traditional for loop: 10 20 30 40 Using forEach method: 10 20 30 40
Explanation:
- For-each loop: Simple and readable, best for reading all elements
- Traditional for loop: Useful when you need the index position
- forEach with Lambda: Modern Java 8+ approach, clean and concise
ArrayList vs Array
Understanding when to use ArrayList instead of regular arrays is important:
Comparison Table
Feature Array ArrayList โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Size Fixed Dynamic (Resizable) Performance Faster Slightly slower Syntax int[] arr = new int[5] ArrayList<Integer> list Type Primitives + Objects Objects only Length/Size arr.length list.size() Adding elements Not possible list.add(element)
โก When to use ArrayList: Choose ArrayList when you don't know the size in advance or need frequent additions/deletions. Use arrays when you have a fixed size and need maximum performance.