Topic 90 of 119 10. Java Collections Framework Interactive Tutorial

Java ArrayList: Dynamic Arrays, Operations, and Performance

10 mins read Last updated: 22 Aug 2026 30,570 views

Direct Answer & Core Concept

ArrayList is one of the most commonly used collection classes in Java. It provides a resizable array that can grow or shrink automatically as elements are added or removed.

Unlike a normal Java array, an ArrayList does not require you to decide its size when creating it. You can add elements dynamically and access them using an index.

For beginners, ArrayList is often the best starting point when you need an ordered collection that allows duplicate values.

Detailed Explanation & Mechanics

What Is ArrayList in Java?

ArrayList is a class in the java.util package that implements the List interface.

It stores elements in an internal array-like structure and automatically manages its capacity as the collection grows.

Main.java
Run Online
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Rahul");
names.add("Priya");
names.add("Amit");
System.out.println(names);

Output:

The important point is that you do not need to specify how many elements the list will contain.


ArrayList Syntax

The basic syntax is:

Main.java
Run Online
ArrayList<Type> listName = new ArrayList<>();

For example:

Main.java
Run Online
ArrayList<String> cities = new ArrayList<>();

An integer list can be created using:

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>();

A list of custom objects can also be created:

Main.java
Run Online
ArrayList<Student> students = new ArrayList<>();

Java generics specify the type of objects that the ArrayList should contain.


Importing ArrayList

Because ArrayList belongs to the java.util package, you normally import it before using it.

Main.java
Run Online
import java.util.ArrayList;

You can also import several collection classes with:

For production code, importing the specific class is often clearer.


Creating an ArrayList

The simplest way to create an ArrayList is:

Main.java
Run Online
ArrayList<String> fruits = new ArrayList<>();

You can then add values:

Main.java
Run Online
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");

The list now contains three elements.

Main.java
Run Online
System.out.println(fruits);

Output:


ArrayList with Initial Capacity

You can optionally provide an initial capacity.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>(20);

This does not mean the list already contains 20 elements.

It means the internal storage can initially accommodate approximately that many elements before additional capacity management is needed.

For example:

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>(100);

The list is still empty:

Main.java
Run Online
System.out.println(numbers.size());

Output:


Adding Elements to ArrayList

The add() method adds an element to the end of the list.

Main.java
Run Online
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println(colors);

Output:


Adding an Element at a Specific Index

You can insert an element at a particular position using:

Example:

Main.java
Run Online
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
languages.add(1, "JavaScript");
System.out.println(languages);

Output:

Main.java
Run Online
[Java, JavaScript, Python, C++]

Elements after the specified position are shifted to make room for the new element.


Accessing ArrayList Elements

Use the get() method to retrieve an element.

Main.java
Run Online
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println(fruits.get(1));

Output:

ArrayList indexes start at 0.

Therefore:

Main.java
Run Online
Index 0 → AppleIndex 1 → BananaIndex 2 → Mango

Updating an ArrayList Element

The set() method replaces an existing element.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");
names.set(1, "Rohan");
System.out.println(names);

Output:

Unlike add(), set() does not increase the size of the list.


Removing Elements from ArrayList

You can remove elements by index.

Main.java
Run Online
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.remove(1);
System.out.println(fruits);

Output:

You can also remove an element by value:

This removes the first matching element.


Important: remove() with Integer

When using ArrayList<Integer>, be careful because remove() has both index-based and object-based behavior.

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

This:

removes the element at index 1.

Result:

But this:

Main.java
Run Online
numbers.remove(Integer.valueOf(20));

removes the value 20.

This distinction is important when working with integer lists.


Finding the Size of an ArrayList

Use the size() method.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");
System.out.println(names.size());

Output:

Remember that size() returns the number of elements currently stored in the list.

It is different from the internal capacity of the ArrayList.


Checking Whether an ArrayList Is Empty

Use:

Example:

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
System.out.println(names.isEmpty());

Output:

After adding an element:

Main.java
Run Online
names.add("Amit");
System.out.println(names.isEmpty());

Output:


Checking Whether an ArrayList Contains an Element

Use:

Example:

Main.java
Run Online
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println(languages.contains("Java"));

Output:

If the element does not exist:

Main.java
Run Online
System.out.println(languages.contains("PHP"));

Output:


Finding an Element's Index

Use indexOf():

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");
System.out.println(names.indexOf("Rahul"));

Output:

If the element is not found, indexOf() returns:

For duplicate elements, indexOf() returns the index of the first matching element.


Finding the Last Occurrence

Use:

Example:

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Amit");
System.out.println(names.lastIndexOf("Amit"));

Output:


Iterating Through an ArrayList

There are several ways to loop through an ArrayList.

Traditional for Loop

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");
for (int i = 0;
i < names.size();
i++) {
    System.out.println(names.get(i));
}

This approach is useful when you need the index.


Enhanced for Loop

Main.java
Run Online
for (String name : names) {
    System.out.println(name);
}

This is usually simpler when you only need the values.


forEach()

You can also use:

Main.java
Run Online
names.forEach(name -> System.out.println(name));

This uses a lambda expression.


Iterator

An Iterator can be used when you need controlled traversal and safe removal during iteration.

Main.java
Run Online
import java.util.ArrayList;
import java.util.Iterator;
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
    String name = iterator.next();
    System.out.println(name);
}

Removing Elements While Iterating

Directly modifying an ArrayList during an enhanced for loop can cause a ConcurrentModificationException.

Avoid:

Main.java
Run Online
for (String name : names) {
    if (name.equals("Rahul")) {
        names.remove(name);
    }
}

Instead, use an Iterator:

Main.java
Run Online
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
    String name = iterator.next();
    if (name.equals("Rahul")) {
        iterator.remove();
    }
}

This is the appropriate iterator-based removal pattern.


Sorting an ArrayList

You can sort a list using Collections.sort().

Main.java
Run Online
import java.util.ArrayList;
import java.util.Collections;
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(50);
numbers.add(10);
numbers.add(30);
numbers.add(20);
Collections.sort(numbers);
System.out.println(numbers);

Output:

Modern Java also supports:

For custom sorting, a Comparator can be supplied.

Main.java
Run Online
numbers.sort((a, b) -> b - a);

For integer subtraction-based comparators, Integer.compare(b, a) is safer in general:

Main.java
Run Online
numbers.sort((a, b) -> Integer.compare(b, a));

Reversing an ArrayList

Use:

Main.java
Run Online
Collections.reverse(list);

Example:

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");
Collections.reverse(names);
System.out.println(names);

Output:


Clearing an ArrayList

The clear() method removes all elements.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.clear();
System.out.println(names);

Output:

After clear(), the list contains no elements.


ArrayList Allows Duplicate Values

An ArrayList can contain the same value multiple times.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Amit");
System.out.println(names);

Output:

This makes ArrayList useful when duplicate entries are meaningful.


ArrayList Maintains Insertion Order

Elements are normally returned in their list order.

Main.java
Run Online
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println(languages);

Output:

The list maintains the sequence in which elements were inserted unless you explicitly modify that ordering.


ArrayList and Null Values

ArrayList can contain null values.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add(null);
names.add("Rahul");
System.out.println(names);

Output:

Whether null is appropriate depends on the application.


ArrayList and Primitive Types

Java collections store objects rather than primitive types.

Therefore, you cannot directly write:

Instead, use the wrapper class:

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>();

Java's autoboxing automatically converts:

to:

when necessary.

Example:

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

ArrayList with Custom Objects

ArrayList becomes particularly useful when storing objects.

Main.java
Run Online
class Student {
    String name;
    int age;
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

You can create a list:

Main.java
Run Online
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Amit", 20));
students.add(new Student("Priya", 21));

You can then access the objects:

Main.java
Run Online
for (Student student : students) {
    System.out.println(student.name);
}

This pattern is common in real Java applications.


ArrayList Performance

Understanding performance is important when choosing between Java collection types.

A simplified performance overview is:

OperationTypical Complexity
get(index)O(1)
set(index, value)O(1)
Add at endAmortized O(1)
Add at middleO(n)
Remove at endO(1)
Remove from middleO(n)
Search with contains()O(n)
indexOf()O(n)
SortingO(n log n) typically

These are typical complexity characteristics rather than guarantees for every possible implementation detail.


Why get() Is Fast

ArrayList uses an array-based storage structure.

Because array elements can be accessed directly by index, this operation is typically constant time:

Main.java
Run Online
String name = names.get(500);

The list does not need to scan all previous elements to find index 500.

This is one of the major advantages of ArrayList.


Why Inserting in the Middle Is Slower

Suppose a list contains:

If you insert X at index 2:

the elements after that position need to be shifted:

As the list becomes larger, more elements may need to move.

Therefore, insertion in the middle is typically O(n).


Why Removing from the Middle Is Slower

Consider:

Removing C requires later elements to shift:

Therefore, removing an element from the middle is typically O(n).


ArrayList Dynamic Resizing

One of the biggest differences between an ordinary array and an ArrayList is automatic capacity management.

Consider:

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

You did not specify the final size.

When the internal storage becomes insufficient, the implementation can allocate a larger backing array and copy existing elements into it.

This allows the list to grow dynamically.

The exact resizing strategy is an implementation detail and should not be relied on as a fixed API rule.


Size vs Capacity

These two concepts are different.

Size means the number of elements currently stored.

Capacity refers to how much internal storage is currently available before another resize may be required.

For example, conceptually:

Main.java
Run Online
Size = 5 elementsCapacity = enough internal storage for more elements

The capacity is not the same thing as the list's logical size.


ArrayList Initial Capacity

If you know approximately how many elements will be added, specifying an initial capacity can reduce some resizing and copying.

Main.java
Run Online
ArrayList<String> users = new ArrayList<>(10000);

This can be useful when creating a large list and the expected size is reasonably predictable.

However, setting a huge capacity without reason can waste memory.


ArrayList vs Array

Both arrays and ArrayList can store multiple values, but they serve different purposes.

FeatureArrayArrayList
SizeFixedDynamically resizable
Syntaxint[]ArrayList<Integer>
Primitive supportYesThrough wrapper types
add() methodNoYes
remove() methodNoYes
get() methodNoYes
Part of Collections FrameworkNoYes
Built-in size methodlengthsize()

Example array:

Main.java
Run Online
int[] numbers = new int[5];

Example ArrayList:

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>();

ArrayList vs LinkedList

Both implement the List interface, but their underlying structures differ.

FeatureArrayListLinkedList
Main structureResizable arrayLinked nodes
Indexed accessFastSlower
Random accessGoodPoor
Memory overheadGenerally lowerGenerally higher
Add at endEfficientEfficient
Middle insertionRequires shiftingCan be efficient after reaching the location
Typical default choice for listsOftenLess often

Do not assume that LinkedList is automatically faster whenever you insert or remove elements. In real applications, the cost of locating the position, memory usage, CPU cache behavior, and workload all matter.

For many ordinary list use cases, ArrayList is the practical default.


ArrayList vs Vector

Vector is an older collection class.

ArrayList is generally preferred for modern single-threaded collection usage.

If multiple threads need shared mutable data, choosing a collection should depend on the actual concurrency requirements rather than simply replacing ArrayList with Vector.


Making an ArrayList Unmodifiable

Modern Java provides convenient factory methods such as:

Main.java
Run Online
List<String> names = List.of("Amit", "Rahul", "Priya");

This creates an unmodifiable list.

Attempting:

will result in an UnsupportedOperationException.

This is different from a normal mutable ArrayList.


Converting ArrayList to Array

You can convert a list into an array using toArray().

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");
String[] array = names.toArray(new String[0]);

Now array contains the list elements.


Converting an Array to ArrayList

For example:

Main.java
Run Online
String[] names = {
    "Amit", "Rahul", "Priya"
};
ArrayList<String> list = new ArrayList<>(Arrays.asList(names));

The resulting ArrayList is mutable.

For modern Java, another option is:

Main.java
Run Online
ArrayList<String> list = new ArrayList<>(List.of("Amit", "Rahul", "Priya"));

Copying an ArrayList

You can create a new mutable list from an existing list:

Main.java
Run Online
ArrayList<String> original = new ArrayList<>();
original.add("Java");
original.add("Python");
ArrayList<String> copy = new ArrayList<>(original);

The new list contains the same element references.

For objects, this is generally a shallow copy rather than a deep copy.


Passing ArrayList to a Method

An ArrayList can be passed to a method like any other object.

Main.java
Run Online
static void printNames(ArrayList<String> names) {
    for (String name : names) {
        System.out.println(name);
    }
}

Call it with:

A more flexible design is often to accept the interface:

Main.java
Run Online
static void printNames(List<String> names) {
    for (String name : names) {
        System.out.println(name);
    }
}

This allows callers to provide other List implementations too.


Returning an ArrayList from a Method

A method can return an ArrayList.

Main.java
Run Online
static ArrayList<String> createNames() {
    ArrayList<String> names = new ArrayList<>();
    names.add("Amit");
    names.add("Rahul");
    names.add("Priya");
    return names;
}

However, returning the more general interface can make the API more flexible:

Main.java
Run Online
static List<String> createNames() {
    return new ArrayList<>(List.of("Amit", "Rahul", "Priya"));
}

Generic ArrayList

Generics provide compile-time type safety.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();

Now the compiler expects String values.

This is valid:

This is not:

Generics reduce accidental type errors and remove the need for many explicit casts.


ArrayList with Streams

ArrayList works naturally with the Java Stream API.

Example:

Main.java
Run Online
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.stream() .filter(n -> n > 20) .forEach(System.out::println);

Output:

Streams are useful for expressing collection-processing operations such as filtering, mapping, and aggregation.


Common ArrayList Mistakes

Mistake 1: Using an Invalid Index

This causes:

Main.java
Run Online
IndexOutOfBoundsException

Example:

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
System.out.println(names.get(1));

Only index 0 exists.


Mistake 2: Confusing Size and Capacity

Creating:

does not create 100 elements.

The list is still empty:

Main.java
Run Online
System.out.println(list.size());

Output:


Mistake 3: Removing During Enhanced for Loop

Avoid modifying the list directly inside an enhanced for loop.

Use an Iterator, removeIf(), or another suitable approach.

For example:

Main.java
Run Online
names.removeIf(name -> name.equals("Rahul"));

Mistake 4: Using ArrayList for Every Problem

ArrayList is excellent for many list-based workloads, but it is not the correct data structure for every situation.

Depending on the problem, you may need:

  • HashSet for unique values

  • HashMap for key-value lookup

  • ArrayDeque for queue or stack behavior

  • TreeSet for sorted unique values

  • TreeMap for sorted key-value data

The correct collection depends on the operations your application performs most frequently.


Best Practices for ArrayList

1. Program to the List interface

Prefer:

Main.java
Run Online
List<String> names = new ArrayList<>();

instead of unnecessarily exposing:

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();

The interface-based approach gives you more implementation flexibility.

2. Specify the generic type

Prefer:

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();

Avoid raw types such as:

Main.java
Run Online
ArrayList names = new ArrayList();

3. Use initial capacity when useful

If you know a large approximate size:

Main.java
Run Online
List<User> users = new ArrayList<>(10000);

This may reduce repeated resizing.

4. Use ArrayDeque for stack/queue workloads

Do not automatically use ArrayList as a stack or queue. Deque implementations are usually better suited to those operations.

5. Avoid unnecessary conversions

If your application already uses a List, avoid repeatedly converting it to arrays or other collection types without a reason.


Complete ArrayList Example

Here is a small program demonstrating several common operations:

Main.java
Run Online
import java.util.ArrayList;
import java.util.Collections;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        // Add elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        // Add at an index
        fruits.add(1, "Orange");
        // Access
        System.out.println("First fruit: " + fruits.get(0));
        // Update
        fruits.set(0, "Grapes");
        // Check
        System.out.println("Contains Mango: " + fruits.contains("Mango"));
        // Remove
        fruits.remove("Orange");
        // Sort
        Collections.sort(fruits);
        // Display
        System.out.println("Fruits: " + fruits);
        // Size
        System.out.println("Size: " + fruits.size());
    }
}

Possible output:

Main.java
Run Online
First fruit: AppleContains Mango: trueFruits:[Banana, Grapes, Mango]Size: 3

When Should You Use ArrayList?

ArrayList is a strong choice when:

  • You need a dynamically sized list.

  • You frequently access elements by index.

  • You want to preserve list order.

  • Duplicate values are allowed.

  • You frequently add elements near the end.

  • You want a straightforward general-purpose List.

For example:

Main.java
Run Online
List<String> products = new ArrayList<>();

is a natural choice for storing an ordered collection of products.


When Should You Avoid ArrayList?

Consider another collection when:

  • You primarily need unique values → Set

  • You need key-value relationships → Map

  • You need efficient queue/deque operations → Deque

  • You need sorted unique values → TreeSet

  • You need sorted key-value data → TreeMap

  • You need specialized concurrent behavior → appropriate concurrent collection

Choosing a collection based on required operations is more important than simply choosing the most familiar class.


ArrayList Quick Revision

ConceptKey Point
Packagejava.util
InterfaceList
StorageResizable array-based structure
DuplicatesAllowed
nullAllowed
IndexingZero-based
Random accessTypically O(1)
Add at endAmortized O(1)
Middle insertionTypically O(n)
Middle removalTypically O(n)
SearchTypically O(n)
SortingTypically O(n log n)
Primitive typesUse wrapper classes
Thread safetyNot synchronized by default

Frequently Asked Questions

Is ArrayList a dynamic array in Java?

Yes. ArrayList provides a resizable, array-backed list abstraction. It automatically manages its internal storage as elements are added.

Does ArrayList allow duplicates?

Yes. An ArrayList can contain duplicate elements.

Does ArrayList maintain insertion order?

Yes. A normal ArrayList maintains the sequence of elements in the list unless you explicitly modify that order.

Is ArrayList synchronized?

No. ArrayList is not synchronized by default. If multiple threads share and modify a list, choose a concurrency strategy appropriate to the application.

What is the default size of an ArrayList?

The logical size of a newly created ArrayList is 0. Its internal capacity is an implementation detail and should not be confused with size().

Why is ArrayList faster for get()?

Because it uses array-based indexed storage, accessing an element by index is typically O(1).

Can ArrayList store primitive data types?

No. Collections store objects, so wrapper types such as Integer, Double, and Character are used. Autoboxing makes primitive values convenient to add.

What happens when ArrayList becomes full?

Its internal storage can be expanded by allocating a larger backing array and copying existing elements. The exact growth policy is implementation-dependent.

Which is better, ArrayList or LinkedList?

There is no universal winner. For many general-purpose list workloads, ArrayList is a good default, especially when indexed access is important. The appropriate choice depends on the operations and workload.

Can ArrayList contain null?

Yes. An ArrayList can contain null elements.

Graphics and Design Ideas

1. ArrayList vs Array Diagram

Create a side-by-side visual showing:

Main.java
Run Online
Java Array[10][20][30][40] Fixed SizeArrayList[10][20][30] → add(40) →[10][20][30][40] Dynamic Growth

2. ArrayList Index Diagram

Show:

Main.java
Run Online
Index: 0 1 2 3 +--------+--------+--------+--------+ | Apple | Banana | Mango | Orange | +--------+--------+--------+--------+

This makes zero-based indexing immediately understandable.

3. ArrayList Performance Graphic

Create a visual table:

Main.java
Run Online
get(index) → O(1) FASTset(index, value) → O(1) FASTadd(end) → O(1)* FASTsearch → O(n) LINEARinsert(middle) → O(n) SHIFTINGremove(middle) → O(n) SHIFTING

Add a small note that add(end) is amortized O(1).

4. Dynamic Resizing Animation

Show:

Main.java
Run Online
Small Storage[ A][ B][ C]↓resizeLarger Storage[ A][ B][ C][][]

Explain visually that resizing may involve creating larger storage and copying existing elements.

5. ArrayList Method Cheat Sheet

Create an infographic containing:

Main.java
Run Online
add() → Addget() → Readset() → Updateremove() → Deletecontains() → Searchsize() → Countclear() → Remove allisEmpty() → Check empty

These visuals can make the tutorial easier for beginners to scan and understand.

Runnable Code Example: Java ArrayList

Java 17+
Main.java
Run Online
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
    public static void main(String[] args) {
        List<String> frameworkList = new ArrayList<>();
        frameworkList.add("Spring Boot");
        frameworkList.add("Quarkus");
        frameworkList.add("Micronaut");
        frameworkList.remove("Quarkus");
        System.out.println("Frameworks count: " + frameworkList.size());
        System.out.println("First Framework: " + frameworkList.get(0));
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

What is the growth policy of ArrayList when it exceeds capacity?

It increases its capacity by 50% (new capacity = current capacity * 1.5).
Q2

When is ArrayList faster than LinkedList?

In almost all real-world scenarios: ArrayList has superior CPU cache locality and O(1) random access, whereas LinkedList has high pointer overhead.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Specify an initial capacity (e.g. new ArrayList<>(expectedSize)) when the number of elements is known in advance to avoid repeated array allocations.