Java ArrayList Master Tutorial: Resizable Arrays & Complete Method Reference

java.util.ArrayList<E> is a resizable-array implementation of the List interface in the Java Collections Framework. Unlike fixed-length native Java arrays, an ArrayList grows its internal Object[] buffer automatically by 50% as elements are added.

Core Strengths: Implements RandomAccess for O(1) constant-time get(index) and set(index, E) lookups, amortized O(1) tail add(E), permits duplicate and null elements, and preserves insertion order.

1. Declaring & Constructing an ArrayList 🔝

Import java.util.ArrayList and choose one of its three constructors:

ArrayList<String> languages = new ArrayList<>();
ArrayList<Integer> marks = new ArrayList<>(50);
ArrayList<String> seeded = new ArrayList<>(Arrays.asList("Java", "PHP", "Python"));

2. Complete Directory of All 20 ArrayList Methods 🔝

Click any method below for its dedicated tutorial, syntax rules, edge cases, and compilable code examples:

Method Tutorial Complexity Summary & Return Value
add(E) / add(int, E) O(1)* / O(n) Appends an element to the tail or inserts at a specific 0-based index.
addAll(Collection) O(n + m) Appends or inserts all elements from another collection in one shift.
get(int index) O(1) Returns the element at the specified 0-based position.
set(int index, E) O(1) Replaces the element at index in place and returns the old value.
remove(int) / remove(Object) O(n) Deletes by 0-based index or deletes the first matching object value.
removeAll(Collection) O(n * m) / O(n) Deletes all occurrences of elements present in the given collection.
removeRange(int, int) O(n) Deletes slice [from, to) in one shift (publicly via subList().clear()).
retainAll(Collection) O(n * m) / O(n) Computes list intersection by keeping only elements present in c.
clear() O(n) Removes all elements and resets size() to 0 while retaining capacity.
size() O(1) Returns the number of elements currently stored in the list.
isEmpty() O(1) Returns true if the list contains zero elements (size() == 0).
contains(Object o) O(n) Returns true if at least one matching element exists in the list.
indexOf(Object o) O(n) Returns the first 0-based index of o, or -1 if not found.
lastIndexOf(Object o) O(n) Scans backward and returns the last 0-based index of o, or -1.
subList(int, int) O(1) Returns a live backed List<E> view of the range [from, to).
listIterator() O(1) Returns a bidirectional ListIterator<E> supporting previous() & set().
toArray() / toArray(T[]) O(n) Exports all list elements into a newly allocated Object[] or typed T[].
clone() O(n) Returns a shallow copy of the ArrayList instance.
ensureCapacity(int) O(n) Pre-allocates internal array capacity to avoid intermediate resizes.
trimToSize() O(n) Shrinks unused backing array capacity down to match size().

3. Core CRUD Walkthrough: Add, Read, Update & Delete 🔝

Combining add(), get(), set(), remove(), and size() in a single workflow:

ArrayList<String> langs = new ArrayList<>(Arrays.asList("Java", "PHP", "Python"));
langs.set(1, "Spring");
langs.remove("Python");
System.out.println("List: " + langs + " | First: " + langs.get(0) + " | Size: " + langs.size());

Terminal Output:

List: [Java, Spring] | First: Java | Size: 2

4. Displaying Elements with For-Loops & Enhanced For-Each 🔝

Because ArrayList implements RandomAccess, both a classic indexed for loop using marks.size() and an enhanced for-each loop run in fast O(n) linear time:

ArrayList<Integer> marks = new ArrayList<>(Arrays.asList(55, 54, 60));
for (int i = 0; i < marks.size(); i++) System.out.print(marks.get(i) + " ");

Terminal Output:

55 54 60

5. Traversing & Filtering Safely with Iterator & ListIterator 🔝

When you need to delete elements while looping, use a generic Iterator<Integer> (or marks.listIterator() for bidirectional movement) and call it.remove() so the list never throws a ConcurrentModificationException:

ArrayList<Integer> marks = new ArrayList<>(Arrays.asList(55, 54, 60));
Iterator<Integer> it = marks.iterator();
while (it.hasNext()) if (it.next() < 55) it.remove();
System.out.println("After Iterator filter: " + marks);

Terminal Output:

After Iterator filter: [55, 60]

6. Searching & Slicing: contains(), indexOf(), lastIndexOf() & subList() 🔝

Locating elements by value and extracting a half-open range view:

ArrayList<String> items = new ArrayList<>(Arrays.asList("A", "B", "C", "B", "D"));
System.out.println("First B: " + items.indexOf("B") + " | Last B: " + items.lastIndexOf("B"));
System.out.println("subList(1, 4): " + items.subList(1, 4));

Terminal Output:

First B: 1 | Last B: 3
subList(1, 4): [B, C, B]

7. Comparison: Native Array vs ArrayList vs LinkedList 🔝

How ArrayList compares against native Java arrays and doubly-linked lists:

Feature Native Array (T[]) ArrayList<E> LinkedList<E>
Resizing Fixed length Dynamic (1.5x growth) Dynamic (node pointers)
Index Lookup O(1) (arr[i]) O(1) (get(i)) O(n) traversal
Primitive Support Yes (int[], double[]) Wrapper classes (Integer) Wrapper classes (Integer)

8. Production Recipe: Sorting an ArrayList Ascending & Descending 🔝

Sorting an ArrayList in place using Collections.sort() and Collections.reverseOrder():

ArrayList<Integer> scores = new ArrayList<>(Arrays.asList(85, 70, 95, 70));
Collections.sort(scores);
System.out.println("Sorted ascending: " + scores);

Terminal Output:

Sorted ascending: [70, 70, 85, 95]

9. Practical Recipe: Combining Bulk Set Operations 🔝

Chaining addAll() and removeAll() to assemble and filter a technology stack list:

ArrayList<String> a = new ArrayList<>(Arrays.asList("Java", "SQL", "HTML"));
a.addAll(Arrays.asList("CSS", "Docker"));
a.removeAll(Arrays.asList("HTML", "CSS"));
System.out.println("Backend stack: " + a);

Terminal Output:

Backend stack: [Java, SQL, Docker]

10. Common Developer Pitfalls & Traps 🔝

Using Primitive Types Directly in Generics: ArrayList<int>

Java generics require reference types, so ArrayList<int> does not compile. Always use the boxed wrapper class ArrayList<Integer>, ArrayList<Double>, or ArrayList<Boolean>.

Unsynchronized Concurrent Mutations Across Threads

ArrayList is not thread-safe. If multiple threads add or remove elements concurrently without external synchronization, use Collections.synchronizedList(new ArrayList<>()) or CopyOnWriteArrayList.

11. Complete Compilable Java Program 🔝

Compile and run this master verification class in any Java environment:

public class ArrayListMasterDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("Java", "PHP"));
        if (!list.isEmpty() && list.size() == 2 && list.get(1).equals("PHP")) {
            System.out.println("All Java ArrayList Master Hub checks passed!");
        }
    }
}

Terminal Output:

All Java ArrayList Master Hub checks passed!

12. Frequently Asked Questions (FAQ) 🔝

What is the default initial capacity of a new ArrayList<>()?

In OpenJDK, new ArrayList<>() starts with a shared empty array and lazily allocates a backing array of capacity 10 when the very first element is added.

When should I prefer ArrayList over LinkedList?

In almost all general-purpose Java code! Because ArrayList stores elements in a contiguous CPU-cache-friendly array, it uses far less memory than LinkedList node objects and offers O(1) index access.

How do I create an ArrayList with initial values in one line?

Use new ArrayList<>(Arrays.asList("Java", "PHP", "Python")) (or new ArrayList<>(List.of("Java", "PHP", "Python")) in Java 9+).

How do I convert an ArrayList back into a plain Java array?

Call list.toArray(new String[0]) (or list.toArray(String[]::new) in Java 11+).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer