DEV Community

Mohammed mhanna
Mohammed mhanna

Posted on

πŸš€ Mastering Data Structures in Java β€” Part 2: ArrayList

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]

Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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);
Enter fullscreen mode Exit fullscreen mode

βœ… 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));
    }
}
Enter fullscreen mode Exit fullscreen mode

🧾 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:

  1. User Management Systems πŸ‘₯

To store and manage dynamic user data (names, IDs, profiles).

ArrayList<User> users = new ArrayList<>();

  1. E-Commerce Platforms πŸ›’

To hold lists of products in a shopping cart or search results.

ArrayList<Product> cartItems = new ArrayList<>();

  1. Mobile Applications πŸ“±

To display items in a RecyclerView (Android) β€” typically backed by an ArrayList.

  1. 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");
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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
Enter fullscreen mode Exit fullscreen mode

βœ… 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));
Enter fullscreen mode Exit fullscreen mode

βœ… 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)