Skip to content
Preview · sample content · Explore all pages

Java ArrayList and indexed access

Last updated: 28 Sept 20263 min read
tutorial
By AITrove Editorial

ArrayList is a resizable-array implementation of List that supports constant-time indexed reads.

Start with the access pattern

If a UI needs the item at row 500 repeatedly, an indexed sequence fits. ArrayList reads that position directly. Inserting near the front shifts later references, so a workload with many such changes needs a separate analysis.

Java
import java.util.ArrayList;
import java.util.List;

public class ReceiptBatch {
    public static void main(String[] args) {
        List<String> receiptIds = new ArrayList<>();
        receiptIds.add("R-104");
        receiptIds.add("R-105");
        receiptIds.set(0, "R-104-corrected");
        System.out.println(receiptIds.get(0));
    }
}

The output is R-104-corrected. Appending may resize the backing array; over many appends the cost is amortized O(1). A resize copies references and can produce a latency spike. The stored objects themselves are not duplicated.

Capacity and public views

Capacity is backing storage; size is the number of accessible elements. ensureCapacity does not add readable elements. get(size) is still invalid even when extra capacity has already been reserved.

subList is a view, not a detached ArrayList. Structural edits to the parent outside the view can invalidate assumptions made by the view. Copy the sublist when a reader needs independent structure, and include that O(k) copying cost.

Connected lessons

Continue with Java LinkedList: operations, internals and failure cases, Java LinkedList quiz.

Common Mistakes

Do not assume an unmodifiable List is an ArrayList. Removing while iterating needs an iterator or a deliberately chosen filter operation. A capacity setting is not an element count.

java
arraylist
Storage details