⛓️🔗🟥 ARRAY LISTS 🟥🔗⛓️

What are Java Array Lists?

An `ArrayList` in Java is a dynamic, resizable array. Unlike traditional arrays that have a fixed size determined at the time of creation, `ArrayLists` can grow or shrink as needed. They are part of the Java Collections Framework and provide more flexibility. Internally, an `ArrayList` uses an array to store its elements. When the internal array becomes full and you try to add a new element, the `ArrayList` automatically creates a new, larger array, copies all the elements from the old array to the new one, and then adds the new element. This dynamic resizing is what makes `ArrayLists` so useful for situations where you don't know the exact number of elements you'll need to store beforehand.

The basic syntax involves declaring and initializing an `ArrayList`. For example: `ArrayList names = new ArrayList<>();`. The `` part specifies the type of elements the list will hold (generics). Common methods include `add(element)` to append an element, `add(index, element)` to insert at a specific position, `get(index)` to retrieve an element, `set(index, element)` to replace an element, `remove(index)` or `remove(object)` to delete elements, and `size()` to get the number of elements. You'd choose an `ArrayList` over a standard array when you need flexibility in size, frequent insertions or deletions (though it's not always the most efficient for these operations in the middle of the list), or when you want to leverage the rich functionality of the Collections Framework.

Annotated Array List Visualization

The ArrayList Index Shifting Problem

A common mistake when working with `ArrayLists` is the "index shifting" problem, especially when iterating and removing elements. When you remove an element at a specific index, all subsequent elements automatically shift one position to the left to fill the gap. This means that if you're iterating through the list and remove an element, the element that was *after* the removed one now occupies the index you just checked. If your loop continues to the next index, you'll skip over this element entirely.


// Example: Removing even numbers, but with a bug
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));

for (int i = 0; i < numbers.size(); i++) {
    if (numbers.get(i) % 2 == 0) {
        numbers.remove(i); // Problem: shifts next elements!
    }
}
// Expected: [1, 3, 5]
// Actual: [1, 3, 4, 6] - Oops! 4 was skipped because 6 shifted into its place.
            

Here are some nice ways to get around this:

Interactive ArrayList Simulation

Enter values and use the controls below to see how an `ArrayList` behaves. Try adding, getting, setting, and removing elements to observe the dynamic nature and index shifting.

Back Home