bhylu.com

Advertisements

Java ArrayList API Reference

ArrayList combines a logical list size with a growable backing capacity. Its methods distinguish insertion, replacement, removal and traversal.

Understand the idea

Index-based methods use zero-based positions, while value-based methods use equality contracts. Some operations return a changed/not-changed flag or an old value, which can be useful information rather than a result to ignore. Backed views and iterators have their own mutation rules. The table lists common operation families without implying that every overload accepts the same arguments.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

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

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>(List.of("Asha", "Dev", "Noor"));
        names.removeIf(name -> name.startsWith("D"));
        names.replaceAll(String::toUpperCase);
        System.out.println(names);
    }
}

Expected output

[ASHA, NOOR]

removeIf applies a predicate to remove matching elements, and replaceAll replaces each remaining value using a function. The source list is mutable here. A List.of value would reject those updates instead of becoming mutable simply because the same method names exist on the interface.

Contracts to look up

API or language termWhat to check
add, addAllInsert one value or a sequence; indexed overloads affect insertion position.
get, setRead or replace an existing indexed element; set does not grow the list.
removeIndex and object-value overloads differ, particularly with Integer lists.
removeAll, retainAll, removeIf, clearRemove by membership, keep membership, remove by predicate or empty the list.
contains, indexOf, lastIndexOfEquality-based search; index methods return -1 for absence.
size, isEmptyLogical element count and its zero test.
ensureCapacity, trimToSizeCapacity management, not element creation or a general memory guarantee.
forEach, iterator, listIterator, spliteratorTraversal APIs with different capabilities and state contracts.
replaceAll, sortMutate element values or ordering according to an operation or comparator.
subListA backed view whose lifetime depends on compatible parent-list changes.
toArrayCopies into an array representation; choose an appropriate typed overload.
cloneA shallow list copy; mutable element objects can still be shared.

Check the official Java documentation for detailed contracts and supported options.

Advertisements