If Arrays are the foundation of data storage in Java, then ArrayListis the evolved version β smarter, flexible, and ready for modern programming needs.
In this post, weβll explore how ArrayListworks, how it differs from arrays, when to use it, and how to get the most out of it in real-world applications.
πΉ What Is an ArrayList?
An ArrayList is a resizable array β part of Javaβs java.util package β that grows or shrinks automatically as elements are added or removed.
Itβs backed by an internal Array, but you donβt have to worry about resizing or managing indexes manually.
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Mohammed");
names.add("Sara");
names.add("Omar");
System.out.println(names); // [Mohammed, Sara, Omar]
πΉ How ArrayList Works Internally
Under the hood, an ArrayList maintains:
A dynamic array to store elements.
A capacity (current size of the internal array).
When the array fills up, a new array with a larger capacity is created, and elements are copied over.
Thatβs why adding elements can sometimes trigger a resize operation β which is more expensive than a simple insertion.
π§© Default capacity grows by 50% each time (since Java 8).
πΉ Declaring and Initializing
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
β Using type inference (Java 7+):
ArrayList<String> fruits = new ArrayList<>();
β Initializing with values:
ArrayList<String> colors = new ArrayList<>(List.of("Red", "Green", "Blue"));
| Method | Description |
|---|---|
add(E e) |
Adds element to the end |
add(int index, E e) |
Inserts element at a specific index |
get(int index) |
Returns element at index |
set(int index, E e) |
Updates element at index |
remove(int index) |
Removes element at index |
size() |
Returns number of elements |
contains(Object o) |
Checks if element exists |
clear() |
Removes all elements |
π Full Reference: ArrayList (Java SE 8 Docs)
πΉ Example: Managing a To-Do List
import java.util.ArrayList;
public class TodoApp {
public static void main(String[] args) {
ArrayList<String> tasks = new ArrayList<>();
tasks.add("Learn Java");
tasks.add("Build Projects");
tasks.add("Read about JVM");
tasks.remove("Read about JVM");
tasks.add(1, "Practice Data Structures");
System.out.println("Tasks: " + tasks);
System.out.println("First task: " + tasks.get(0));
}
}
π§Ύ Output:
Tasks: [Learn Java, Practice Data Structures, Build Projects]
First task: Learn Java
πΉ Differences Between Array and ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Type | Can hold primitives and objects | Only objects |
| Syntax | int[] arr = new int[5]; |
ArrayList<Integer> list = new ArrayList<>(); |
| Performance | Slightly faster for fixed data | Slightly slower (resize overhead) |
| Utilities | No built-in utilities | Rich methods (add, remove, contains, etc.) |
π Where ArrayLists Are Used in Real-World Projects
ArrayLists are used everywhere in real-world Java applications β especially when you donβt know the size of your data beforehand:
- User Management Systems π₯
To store and manage dynamic user data (names, IDs, profiles).
ArrayList<User> users = new ArrayList<>();
- E-Commerce Platforms π
To hold lists of products in a shopping cart or search results.
ArrayList<Product> cartItems = new ArrayList<>();
- Mobile Applications π±
To display items in a RecyclerView (Android) β typically backed by an ArrayList.
- Log and Event Systems π§Ύ
To accumulate logs dynamically before writing to a file or database.
ArrayList<String> logs = new ArrayList<>();
logs.add("Application started");
logs.add("User logged in");
πΉ Performance Insights
| Operation | Time Complexity | Notes |
|---|---|---|
| Access (get/set) | O(1) | Direct index access |
| Insert at end | Amortized O(1) | Resizing may occur |
| Insert/remove at middle | O(n) | Elements shifted |
| Search | O(n) | Linear search |
| Clear | O(n) | Removes all elements |
π§ Pro Tip:
If you plan heavy insertion/removal operations, consider using a LinkedList
instead.
πΉ Avoid Common Mistakes
π« Forgetting Generics:
ArrayList list = new ArrayList(); // β Not type-safe
list.add("Hello");
list.add(123); // Compiles, fails later
β Correct:
ArrayList<String> list = new ArrayList<>();
π« Using == for value comparison:
if (list.get(0) == "Hello") // β
β Use .equals() instead:
if (list.get(0).equals("Hello"))
Pro Tips to Master ArrayList
β Set an initial capacity if you know approximate data size:
ArrayList<Integer> list = new ArrayList<>(1000);
This avoids multiple costly resize operations.
β
Convert between Array and ArrayList:
String[] arr = {"A", "B", "C"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr));
β Use streams with ArrayList:
list.stream().filter(x -> x.startsWith("A")).forEach(System.out::println);
π¬ Final Thought
ArrayLists bring the power of dynamic storage while keeping the simplicity of arrays.
Master them, and youβll unlock a crucial step toward understanding Java Collections Framework.
Next up in the series:
π LinkedList in Java β When You Need Fast Insertions
Top comments (0)