What is ArrayList?
The ArrayList class in Java is part of the java.util package and provides a resizable array implementation. Unlike regular arrays in Java, which have a fixed size, an ArrayList can dynamically grow or shrink as needed. This makes it an essential part of Java’s Collections Framework and an excellent choice for situations where you need a flexible and efficient way to manage a collection of elements.
Why Use an ArrayList?
- Dynamic Size: Unlike arrays, ArrayList can automatically adjust its size when you add or remove elements.
- Easy to Use: Provides built-in methods for adding, removing, searching, and iterating through elements.
- Flexible Data Types: Supports both primitive and custom objects using generics.
- Part of Java Collections Framework: Fully integrated with Java’s utilities for sorting, searching and filtering.
Key Features of ArrayList
- Resizable: Automatically resizes itself when the size limit is reached.
- Maintains Order: Preserves the insertion order of elements.
- Allows Duplicates: Accepts duplicate values.
- Zero-Based Indexing: Similar to arrays, indexing starts at 0.
- Not Thread-Safe: Requires external synchronization for multi-threaded environments.
How to Use ArrayList
1. Import the ArrayList Class
The ArrayList class is part of the java.util package. You must import it to use it in your program.
import java.util.ArrayList;
2. Create an ArrayList
An ArrayList can store elements of any type by using generics. For example:
- ArrayList<String>: Stores strings.
- ArrayList<Integer>: Stores integers.
ArrayList<String> list = new ArrayList<>();
Common Methods of ArrayList
Method | Description |
---|---|
add(E element) | Adds an element to the end of the list. |
add(int index, E element) | Inserts an element at a specific position. |
remove(int index) | Removes the element at the specified index. |
get(int index) | Retrieves the element at the specified index. |
set(int index, E element) | Replaces the element at the specified index. |
size() | Returns the number of elements in the list. |
clear() | Removes all elements from the list. |
contains(Object o) | Checks if the list contains a specific element. |
isEmpty() | Checks if the list is empty. |
Examples of Using ArrayList
1. Basic Operations
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> fruits = new ArrayList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Display the ArrayList
System.out.println("Fruits: " + fruits);
// Get an element by index
System.out.println("First Fruit: " + fruits.get(0));
// Remove an element
fruits.remove(1);
System.out.println("After Removal: " + fruits);
// Update an element
fruits.set(1, "Blueberry");
System.out.println("After Update: " + fruits);
// Check size
System.out.println("Total Fruits: " + fruits.size());
}
}
Output:
Fruits: [Apple, Banana, Cherry]
First Fruit: Apple
After Removal: [Apple, Cherry]
After Update: [Apple, Blueberry]
Total Fruits: 2
2. Iterating Through an ArrayList
You can iterate through an ArrayList using loops or iterators.
Using a For-Each Loop
for (String fruit : fruits) {
System.out.println(fruit);
}
Using a For Loop
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
3. Working with Integer ArrayList
import java.util.ArrayList;
public class IntegerArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Add numbers
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Display numbers
System.out.println("Numbers: " + numbers);
// Find sum of all elements
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum);
}
}
Output:
Numbers: [10, 20, 30]
Sum: 60
4. Sorting an ArrayList
The Collections.sort() method is used to sort an ArrayList.
import java.util.ArrayList;
import java.util.Collections;
public class SortingExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("John");
names.add("Alice");
names.add("Bob");
// Sort the list
Collections.sort(names);
// Display sorted list
System.out.println("Sorted Names: " + names);
}
}
Output:
Sorted Names: [Alice, Bob, John]
Limitations of ArrayList
- Not Synchronized: ArrayList is not thread-safe. Use Collections.synchronizedList() for thread safety.
- Performance: Adding or removing elements in the middle of the list is slower compared to LinkedList due to shifting of elements.
- Fixed Data Type: Requires generics to specify the data type, unlike HashMap, which allows mixed types.