Skip to main content

Java Collections

ArrayList

Complete lesson for ArrayList using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — ArrayList

Section: Java Collections. ArrayList — the resizable array you will use every day: creating, adding, accessing, removing, searching, sorting, converting, custom objects, internals, complexity, and pitfalls with real-life examples.

What is ArrayList?

  • ArrayList is a resizable array in java.util. It implements the List interface, keeps insertion order, allows duplicates, and gives fast access by index.
  • Unlike a normal array, you do not fix its size. It grows automatically when you add elements and shrinks logically when you remove them.
  • Real life: a to-do list. You keep adding tasks, tick some off, push an urgent one to the top, and read task number 1 directly.
  • It is the most used collection in Java and the best default choice whenever you need a list.
import java.util.ArrayList;

public class TodoList {
    public static void main(String[] args) {
        ArrayList<String> todo = new ArrayList<>();    // starts empty, grows as needed
        todo.add("Pay electricity bill");
        todo.add("Buy vegetables");
        todo.add("Call mom");
        System.out.println(todo);                       // [Pay electricity bill, Buy vegetables, Call mom]
        System.out.println("Tasks: " + todo.size());    // 3

        todo.remove("Buy vegetables");                  // done
        todo.add(0, "Submit assignment");               // urgent: put on top
        System.out.println(todo);                       // [Submit assignment, Pay electricity bill, Call mom]
        System.out.println("First task: " + todo.get(0));
    }
}

Features of ArrayList

FeatureMeaning
Dynamic sizeGrows automatically (about 1.5 times) when full
OrderedKeeps elements in insertion order
Index basedget(i) and set(i, e) are fast; index starts at 0
DuplicatesAllowed
nullAllowed, even many times
Objects onlyPrimitives are auto-boxed: int becomes Integer
Not synchronizedNot thread-safe without extra locking
Fail-fast iteratorThrows ConcurrentModificationException if changed during a for-each
InterfacesList, RandomAccess, Cloneable, Serializable
Backing storeAn internal Object[] array

Creating an ArrayList

  • Declare with the interface (List<String>) and create with the class (new ArrayList<>()). The diamond <> lets Java infer the type.
  • Give an initial capacity when you know roughly how many elements you will add, to avoid repeated resizing.
  • Real life: booking a hall for about 500 guests up front, instead of moving to a bigger hall three times during the party.
Constructor / wayMeaningExample
new ArrayList<>()Empty list; capacity 10 is allocated on the first addList<String> names = new ArrayList<>();
new ArrayList<>(int capacity)Empty list with room for that many elementsnew ArrayList<>(500)
new ArrayList<>(Collection c)Copy of another collection, fully modifiablenew ArrayList<>(List.of("A", "B"))
var list = new ArrayList<Type>()Local variable type inference (Java 10)var marks = new ArrayList<Integer>();
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CreateArrayList {
    public static void main(String[] args) {
        ArrayList<String> a = new ArrayList<>();                     // 1. empty
        List<String> b = new ArrayList<>(500);                       // 2. initial capacity for ~500 guests
        List<String> c = new ArrayList<>(List.of("Red", "Green"));   // 3. copy of another collection
        List<Integer> d = new ArrayList<>(Arrays.asList(5, 3, 8));   // 4. from Arrays.asList
        var e = new ArrayList<Double>();                             // 5. with var (Java 10)

        a.add("Hello");
        c.add("Blue");                                               // copies are fully modifiable
        d.add(1);
        e.add(99.5);
        System.out.println(a + " " + b.size() + " " + c + " " + d + " " + e);
        // [Hello] 0 [Red, Green, Blue] [5, 3, 8, 1] [99.5]
    }
}

Differences between array and ArrayList

PointArrayArrayList
SizeFixed at creationGrows and shrinks automatically
Syntaxint[] a = new int[5];List<Integer> a = new ArrayList<>();
PrimitivesYes: int[]No: uses wrappers like Integer
Length / sizea.length (field)list.size() (method)
Accessa[i]list.get(i)
Change elementa[i] = xlist.set(i, x)
Add / removeNot possible (create a new array)add, remove, removeIf, clear
Built-in helpersThrough Arrays classMany methods plus Collections
Speed / memorySlightly faster, less memorySmall overhead, much more convenient
Multi-dimensionalint[][]List<List<Integer>>
Real lifeEgg tray with 12 fixed slotsStretchable shopping bag

Important ArrayList methods

MethodWhat it doesExample
add(e)Adds at the endcart.add("Milk")
add(i, e)Inserts at index i (shifts the rest right)cart.add(0, "Bread")
addAll(c) / addAll(i, c)Adds every element of another collectioncart.addAll(List.of("Eggs", "Tea"))
get(i)Element at index icart.get(2)
set(i, e)Replaces the element at index i; returns the old onecart.set(1, "Butter")
remove(int i)Removes by indexcart.remove(0)
remove(Object o)Removes the first matching elementcart.remove("Milk")
removeIf(predicate)Removes all elements matching a conditioncart.removeIf(x -> x.isEmpty())
removeAll(c) / retainAll(c)Difference / intersection with another collectioncart.removeAll(outOfStock)
contains(o)True if the element existscart.contains("Tea")
indexOf(o) / lastIndexOf(o)First / last position, or -1cart.indexOf("Tea")
size() / isEmpty()Count / empty checkcart.size()
clear()Removes all elementscart.clear()
sort(comparator)Sorts the list (null = natural order)cart.sort(Comparator.naturalOrder())
replaceAll(operator)Transforms every elementcart.replaceAll(String::toUpperCase)
forEach(action)Runs an action for each elementcart.forEach(System.out::println)
subList(from, to)View of a range (to excluded)cart.subList(0, 3)
toArray(new T[0])Copies into an arraycart.toArray(new String[0])
iterator() / listIterator()Cursor for safe removal or two-way loopingcart.iterator()
ensureCapacity(n) / trimToSize()Reserve space / release unused spacelist.ensureCapacity(10_000)

Adding and accessing elements

  • add(e) appends at the end; add(i, e) inserts at a position and shifts later elements one place right.
  • get(i) reads and set(i, e) replaces. Valid indexes are 0 to size() - 1; anything else throws IndexOutOfBoundsException.
  • Real life: a train. Coaches are added at the end, an AC coach can be inserted right after the engine, and coach number 3 can be reached directly.
import java.util.ArrayList;
import java.util.List;

public class TrainCoaches {
    public static void main(String[] args) {
        List<String> train = new ArrayList<>();
        train.add("Engine");
        train.add("S1");
        train.add("S2");
        train.add("Guard");
        train.add(3, "S3");                              // insert before Guard
        train.addAll(1, List.of("A1", "B1"));            // AC coaches right after the engine

        System.out.println(train);                       // [Engine, A1, B1, S1, S2, S3, Guard]
        System.out.println("Coach at 2: " + train.get(2));            // B1
        String old = train.set(4, "S2-Pantry");          // replace a coach
        System.out.println("Replaced " + old);           // Replaced S2
        System.out.println("Total coaches: " + train.size());         // 7
        System.out.println("Last: " + train.get(train.size() - 1));   // Guard
        // train.get(7);                                 // IndexOutOfBoundsException
    }
}

Removing elements

  • remove(Object) deletes the first match; remove(int) deletes by position; removeIf deletes everything matching a condition; clear empties the list.
  • Trap: on List<Integer>, remove(1) removes the element at index 1, not the value 1. Use remove(Integer.valueOf(1)) for the value.
  • Real life: guests leaving a party — by name, by seat number, or "everyone whose cab has arrived".
import java.util.ArrayList;
import java.util.List;

public class RemoveDemo {
    public static void main(String[] args) {
        List<String> guests = new ArrayList<>(List.of("Asha", "Ravi", "Kiran", "Meena", "Ravi", "John"));
        guests.remove("Ravi");                       // removes the FIRST Ravi only
        guests.remove(0);                            // removes by index: Asha
        guests.removeIf(g -> g.startsWith("J"));     // removes John
        System.out.println(guests);                  // [Kiran, Meena, Ravi]

        List<Integer> tokens = new ArrayList<>(List.of(10, 20, 30, 1));
        tokens.remove(1);                            // index 1: removes 20
        tokens.remove(Integer.valueOf(1));           // value 1: removes 1
        System.out.println(tokens);                  // [10, 30]

        guests.clear();
        System.out.println(guests.isEmpty());        // true
    }
}

Searching in an ArrayList

  • contains, indexOf, and lastIndexOf scan from the start, so they take O(n) time. They use equals() to compare.
  • For a sorted list, Collections.binarySearch finds an element in O(log n).
  • Real life: a teacher calling out names on a roll-call sheet until the right student answers.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RollCall {
    public static void main(String[] args) {
        List<String> students = new ArrayList<>(List.of("Asha", "Ravi", "Kiran", "Ravi"));

        System.out.println(students.contains("Kiran"));      // true
        System.out.println(students.indexOf("Ravi"));        // 1
        System.out.println(students.lastIndexOf("Ravi"));    // 3
        System.out.println(students.indexOf("Meena"));       // -1 (not found)

        Collections.sort(students);                          // [Asha, Kiran, Ravi, Ravi]
        System.out.println(Collections.binarySearch(students, "Kiran"));   // 1
    }
}

Iterating an ArrayList

  • Index loop when you need the position, for-each to simply read, Iterator to remove while looping, ListIterator to replace or go backwards, and forEach for short lambda code.
  • Real life: a restaurant manager walking through pending orders, removing cancelled ones and marking the rest as confirmed.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IterateOrders {
    public static void main(String[] args) {
        List<String> orders = new ArrayList<>(List.of("Pizza", "Burger", "Cancelled", "Pasta"));

        for (int i = 0; i < orders.size(); i++) {            // index loop: position needed
            System.out.println((i + 1) + ". " + orders.get(i));
        }

        for (String o : orders) {                            // for-each: just read
            System.out.print(o + " ");
        }
        System.out.println();

        Iterator<String> it = orders.iterator();             // Iterator: remove safely
        while (it.hasNext()) {
            if (it.next().equals("Cancelled")) it.remove();
        }

        ListIterator<String> li = orders.listIterator();     // ListIterator: replace while looping
        while (li.hasNext()) {
            li.set(li.next().toUpperCase());
        }

        orders.forEach(o -> System.out.print(o + " "));      // forEach + lambda
        System.out.println();                                // PIZZA BURGER PASTA
    }
}

Sorting an ArrayList

  • Collections.sort(list) or list.sort(null) sorts in natural order (numbers ascending, strings A to Z with capitals first).
  • Pass a Comparator for other orders: Comparator.reverseOrder(), String.CASE_INSENSITIVE_ORDER, or Comparator.comparing(...) chains.
  • Real life: arranging a class leaderboard by marks, then by name for ties.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Leaderboard {
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<>(List.of(78, 95, 62, 88, 95, 40));
        Collections.sort(marks);                                 // ascending
        System.out.println(marks);                               // [40, 62, 78, 88, 95, 95]
        marks.sort(Comparator.reverseOrder());                   // descending
        System.out.println(marks);                               // [95, 95, 88, 78, 62, 40]

        List<String> names = new ArrayList<>(List.of("ravi", "Asha", "kiran", "Meena"));
        Collections.sort(names);                                 // capitals come first
        System.out.println(names);                               // [Asha, Meena, kiran, ravi]
        names.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println(names);                               // [Asha, kiran, Meena, ravi]
        names.sort(Comparator.comparing(String::length).thenComparing(String.CASE_INSENSITIVE_ORDER));
        System.out.println(names);                               // [Asha, ravi, kiran, Meena]
    }
}

ArrayList of custom objects

  • Store your own objects like Employee or Product. Override toString() for readable printing.
  • Override equals() (and hashCode()) so that contains, indexOf, and remove(Object) find logically equal objects.
  • Sort them with Comparator.comparing(...) on any field.
  • Real life: an HR system keeping a list of employees, giving everyone a 10% hike, and listing them by salary.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

class Employee {
    private final int id;
    private final String name;
    private double salary;

    Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    double getSalary() { return salary; }
    void raise(double percent) { salary += salary * percent / 100; }

    @Override
    public boolean equals(Object o) {                 // used by contains / indexOf / remove(Object)
        return o instanceof Employee e && e.id == id;
    }

    @Override
    public int hashCode() { return Objects.hash(id); }

    @Override
    public String toString() { return id + ":" + name + ":" + salary; }
}

public class EmployeeList {
    public static void main(String[] args) {
        List<Employee> staff = new ArrayList<>();
        staff.add(new Employee(101, "Asha", 50000));
        staff.add(new Employee(102, "Ravi", 42000));
        staff.add(new Employee(103, "Kiran", 61000));

        System.out.println(staff.contains(new Employee(102, "", 0)));    // true: equal by id
        staff.forEach(e -> e.raise(10));                                   // 10% hike for all
        staff.sort(Comparator.comparingDouble(Employee::getSalary).reversed());
        staff.forEach(System.out::println);
        // 103:Kiran:67100.0
        // 101:Asha:55000.0
        // 102:Ravi:46200.0
    }
}

Converting between arrays and ArrayList

  • Arrays.asList(array) returns a fixed-size list backed by the array: set works (and changes the array), but add and remove throw UnsupportedOperationException.
  • Wrap it for a real, resizable copy: new ArrayList<>(Arrays.asList(array)).
  • Go back with list.toArray(new String[0]). For int[], use streams with boxed() and mapToInt.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConvertDemo {
    public static void main(String[] args) {
        String[] fruits = { "Mango", "Apple", "Banana" };

        List<String> fixed = Arrays.asList(fruits);           // fixed-size view backed by the array
        fixed.set(0, "Guava");                                // OK: also changes fruits[0]
        // fixed.add("Kiwi");                                 // UnsupportedOperationException
        System.out.println(fruits[0]);                        // Guava

        List<String> basket = new ArrayList<>(Arrays.asList(fruits));    // resizable copy
        basket.add("Kiwi");
        System.out.println(basket);                           // [Guava, Apple, Banana, Kiwi]

        String[] back = basket.toArray(new String[0]);        // ArrayList to array
        System.out.println(back.length);                      // 4

        int[] marks = { 70, 85, 90 };
        List<Integer> markList = new ArrayList<>(Arrays.stream(marks).boxed().toList());  // int[] to List
        int[] again = markList.stream().mapToInt(Integer::intValue).toArray();          // List to int[]
        System.out.println(markList + " " + again.length);    // [70, 85, 90] 3
    }
}

ArrayList with primitive values (autoboxing)

  • ArrayList<int> is not allowed. Use wrapper types: Integer, Double, Character, Boolean.
  • Java converts automatically: list.add(5) boxes 5 into an Integer; int x = list.get(0) unboxes it.
  • Compare wrapper values with equals(), never ==. Only values from -128 to 127 are cached, so == works by accident for small numbers and fails for bigger ones.
  • Unboxing a null element into an int throws NullPointerException.
import java.util.ArrayList;
import java.util.List;

public class BoxingTraps {
    public static void main(String[] args) {
        List<Integer> x = new ArrayList<>(List.of(127, 1000));
        List<Integer> y = new ArrayList<>(List.of(127, 1000));

        System.out.println(x.get(0) == y.get(0));         // true  (cached -128 to 127)
        System.out.println(x.get(1) == y.get(1));         // false (different objects)
        System.out.println(x.get(1).equals(y.get(1)));    // true  (always use equals)

        int sum = 0;
        for (int v : x) {                                 // auto-unboxing
            sum += v;
        }
        System.out.println("Sum = " + sum);               // 1127

        List<Integer> withNull = new ArrayList<>();
        withNull.add(null);
        try {
            int bad = withNull.get(0);                    // unboxing null
            System.out.println(bad);
        } catch (NullPointerException e) {
            System.out.println("Cannot unbox null");
        }
    }
}

Differences between ArrayList and LinkedList

PointArrayListLinkedList
StructureDynamic arrayDoubly linked nodes
get(i) / set(i)O(1)O(n)
add at endAmortized O(1)O(1)
add / remove at frontO(n) (shifts elements)O(1)
Insert in the middleO(n) shiftingO(n) to find the spot, then O(1)
MemoryCompact arrayExtra node objects with two pointers each
CPU cache localityExcellentPoor
Implements DequeNoYes
RandomAccess markerYesNo
Real lifeNumbered seats in a theatreA treasure hunt where each clue points to the next
Default choiceYesRarely (use ArrayDeque for queues)
L2

Advanced — ArrayList

How ArrayList works internally

  • Inside is an Object[] elementData and an int size. size is how many elements you stored; capacity is the length of the internal array.
  • A new ArrayList<>() starts with a shared empty array. The first add allocates capacity 10.
  • When the array is full, grow() creates a bigger array of old + old / 2 (about 1.5 times) and copies elements with Arrays.copyOf. Growth sequence: 10, 15, 22, 33, 49, 73, 109, ...
  • Removing does not shrink the array. Call trimToSize() to release unused space, or ensureCapacity(n) to grow once in advance.
  • Real life: a theatre group that moves to a hall 1.5 times bigger whenever every seat is taken. Moving is slow, but it happens rarely, so the average cost per new member stays small (amortized O(1)).
import java.util.Arrays;

public class MiniArrayList<E> {
    private Object[] data = new Object[2];
    private int size = 0;

    public void add(E e) {
        if (size == data.length) {                                    // full: grow
            int newCapacity = data.length + (data.length >> 1) + 1;  // about 1.5 times
            data = Arrays.copyOf(data, newCapacity);                 // copy to a bigger array
            System.out.println("Grew to capacity " + newCapacity);
        }
        data[size++] = e;
    }

    @SuppressWarnings("unchecked")
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + ", size " + size);
        }
        return (E) data[index];                                      // O(1): direct array access
    }

    public int size() {
        return size;
    }

    public static void main(String[] args) {
        MiniArrayList<String> list = new MiniArrayList<>();
        for (String s : new String[] { "a", "b", "c", "d", "e", "f" }) {
            list.add(s);
        }
        System.out.println("size " + list.size() + ", element 4 = " + list.get(4));
        // Grew to capacity 4, Grew to capacity 7, size 6, element 4 = e
    }
}

Time complexity of ArrayList operations

OperationTimeWhy
get(i), set(i, e)O(1)Direct array index
add(e) at endAmortized O(1)Occasional resize copies all elements
add(i, e) in the middle or frontO(n)Shifts later elements right
remove(i) in the middle or frontO(n)Shifts later elements left
remove(size() - 1) last elementO(1)Nothing to shift
contains, indexOf, remove(Object)O(n)Linear scan with equals
removeIf(predicate)O(n)Single pass, compacts once
sortO(n log n)TimSort
Collections.binarySearch on a sorted listO(log n)Uses RandomAccess
size(), isEmpty()O(1)Stored field

Fail-fast iteration and ConcurrentModificationException

  • ArrayList counts structural changes in a field called modCount. The iterator remembers it and throws ConcurrentModificationException if the list changes behind its back.
  • Calling list.remove or list.add inside a for-each loop is the classic mistake.
  • Fixes: removeIf, Iterator.remove(), or a backward index loop.
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

public class RemoveEvens {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        try {
            for (Integer n : nums) {
                if (n % 2 == 0) nums.remove(n);       // changing the list inside for-each
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("CME: do not modify inside for-each");
        }

        List<Integer> a = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        a.removeIf(n -> n % 2 == 0);                  // fix 1: removeIf
        System.out.println(a);                        // [1, 3, 5]

        List<Integer> b = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        for (int i = b.size() - 1; i >= 0; i--) {     // fix 2: backward index loop
            if (b.get(i) % 2 == 0) b.remove(i);
        }
        System.out.println(b);                        // [1, 3, 5]
    }
}

subList is a view, not a copy

  • subList(from, to) returns a window onto the original list (from included, to excluded). Changes through it affect the original.
  • list.subList(a, b).clear() is the fastest way to remove a range.
  • If the original list is structurally changed directly, the old sublist becomes invalid and throws ConcurrentModificationException.
  • Need an independent copy? Use new ArrayList<>(list.subList(a, b)).
import java.util.ArrayList;
import java.util.List;

public class SubListDemo {
    public static void main(String[] args) {
        List<String> songs = new ArrayList<>(List.of("S1", "S2", "S3", "S4", "S5"));

        List<String> firstThree = songs.subList(0, 3);       // view of S1, S2, S3
        firstThree.set(0, "S1-Remix");                       // writes through
        System.out.println(songs);                           // [S1-Remix, S2, S3, S4, S5]

        List<String> copy = new ArrayList<>(songs.subList(3, 5));   // independent copy
        firstThree.clear();                                  // removes the range from songs
        System.out.println(songs + " " + copy);              // [S4, S5] [S4, S5]

        songs.add("S6");                                     // structural change to the parent
        // firstThree.size();                                // ConcurrentModificationException
    }
}

Differences between new ArrayList, Arrays.asList, and List.of

Pointnew ArrayList<>(...)Arrays.asList(...)List.of(...)
add / removeYesNo: UnsupportedOperationExceptionNo: UnsupportedOperationException
setYesYes (writes to the array)No
null elementsAllowedAllowedNot allowed: NullPointerException
Backed by an array?Own internal arrayYes, the array you passedOwn immutable storage
Java version1.21.29
Use whenYou need a normal, changeable listQuick fixed-size view of an arrayConstant data that never changes

Differences between ArrayList, Vector, and CopyOnWriteArrayList

PointArrayListVectorCopyOnWriteArrayList
Thread-safeNoYes (every method synchronized)Yes (copy on every write)
Speed (single thread)FastestSlower (locking)Slow writes, fast reads
GrowthAbout 1.5 times2 timesNew array on every write
IteratorFail-fastFail-fastSnapshot, never throws CME
Legacy?NoYes (Java 1.0)No (java.util.concurrent)
Use whenDefault listOld code onlyMany readers, rare writers (listeners)

ArrayList and threads

  • ArrayList is not thread-safe. Two threads adding at once can lose elements or throw ArrayIndexOutOfBoundsException.
  • Collections.synchronizedList(new ArrayList<>()) locks each call, but you must still hold the lock while iterating.
  • For many reads and few writes, use CopyOnWriteArrayList. For producer-consumer work, use a BlockingQueue instead of a list.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SafeList {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> unsafe = new ArrayList<>();
        List<Integer> safe = Collections.synchronizedList(new ArrayList<>());

        Runnable task = () -> {
            for (int i = 0; i < 10_000; i++) {
                try {
                    unsafe.add(i);
                } catch (ArrayIndexOutOfBoundsException e) {
                    // can happen when two threads resize at once
                }
                safe.add(i);
            }
        };
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("unsafe size: " + unsafe.size());   // often less than 20000
        System.out.println("safe size: " + safe.size());       // always 20000

        synchronized (safe) {                                   // lock while iterating
            long evens = safe.stream().filter(n -> n % 2 == 0).count();
            System.out.println("even numbers: " + evens);       // 10000
        }
    }
}

Sequenced methods (Java 21) and streams

  • Java 21 adds getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast(), and reversed() to ArrayList through SequencedCollection.
  • Streams make filtering, mapping, and summarising an ArrayList short and readable.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ModernArrayList {
    record Product(String name, String category, int price) { }

    public static void main(String[] args) {
        List<String> queue = new ArrayList<>(List.of("Asha", "Ravi", "Kiran"));
        System.out.println(queue.getFirst() + " / " + queue.getLast());   // Asha / Kiran
        queue.addFirst("VIP");
        queue.removeLast();
        System.out.println(queue.reversed());                             // [Ravi, Asha, VIP]

        List<Product> products = new ArrayList<>(List.of(
            new Product("Earbuds", "Electronics", 1999),
            new Product("Kurta", "Fashion", 899),
            new Product("Charger", "Electronics", 799),
            new Product("Watch", "Electronics", 2999)
        ));

        List<String> electronics = products.stream()
            .filter(p -> p.category().equals("Electronics"))
            .map(Product::name)
            .sorted()
            .toList();
        int total = products.stream().mapToInt(Product::price).sum();
        Product costliest = products.stream().max(Comparator.comparingInt(Product::price)).orElseThrow();

        System.out.println(electronics);                  // [Charger, Earbuds, Watch]
        System.out.println("Total: Rs." + total);         // 6696
        System.out.println("Costliest: " + costliest.name());   // Watch
    }
}

ArrayList performance tips

DoDo not
Pre-size with new ArrayList<>(expected) for big listsLet a million-element list resize 30 times
Use removeIf for bulk removalCall remove(i) in a forward loop (skips elements, O(n²))
Use ArrayDeque when you add or remove at the front oftenUse list.remove(0) as a queue
Use a HashSet for frequent contains checksCall list.contains inside a big loop
Declare as List<T>Expose ArrayList<T> in method signatures
Use List.of / List.copyOf for constantsReturn internal mutable lists from getters
Use subList(a, b).clear() to delete a rangeRemove a range one element at a time
Compare elements with equalsCompare Integer elements with ==
L3

Tricky Interview Points

Q1) What is an ArrayList?

Answer A resizable array implementation of the List interface in java.util. It keeps insertion order, allows duplicates and null, and offers O(1) index access.

Q2) What is the difference between an array and an ArrayList?

Answer An array has a fixed size and can hold primitives. An ArrayList grows automatically, holds only objects (using wrappers), and provides methods like add, remove, contains, and sort.

Q3) What is the default capacity of an ArrayList?

Answer 10, allocated lazily on the first add. A new ArrayList starts with a shared empty array.

Q4) How does ArrayList grow?

Answer When size equals capacity, it creates a new array about 1.5 times larger (old + old/2) and copies the elements with Arrays.copyOf. Adding at the end is amortized O(1).

Q5) What is the difference between size and capacity?

Answer Size is the number of elements stored. Capacity is the length of the internal array, which is always greater than or equal to size.

Q6) Why is get(i) O(1) in ArrayList?

Answer Elements are stored in a contiguous array, so the element at index i is reached directly without scanning.

Q7) Why are add(i, e) and remove(i) O(n)?

Answer All elements after index i must be shifted one position right or left using System.arraycopy.

Q8) What happens with remove(1) on an ArrayList<Integer>?

Answer It calls remove(int index) and removes the element at index 1. To remove the value 1, use remove(Integer.valueOf(1)).

Q9) Can ArrayList store primitive types?

Answer No. It stores objects only. Primitives are auto-boxed into wrapper classes such as Integer and Double.

Q10) Can ArrayList contain null and duplicates?

Answer Yes, both. It can hold many nulls and repeated values.

Q11) Is ArrayList synchronized?

Answer No. Use Collections.synchronizedList, CopyOnWriteArrayList, or external locking for concurrent access.

Q12) What is the difference between ArrayList and Vector?

Answer Vector is a legacy class whose methods are synchronized and which doubles its size when growing. ArrayList is unsynchronized, faster, and grows by about 1.5 times.

Q13) What is the difference between ArrayList and LinkedList?

Answer ArrayList uses a dynamic array with O(1) index access. LinkedList uses doubly linked nodes with O(1) insertion at the ends but O(n) index access and more memory. ArrayList is the usual choice.

Q14) Why do you get ConcurrentModificationException?

Answer Because the list was structurally modified during iteration by something other than the iterator, for example list.remove inside a for-each loop. Use Iterator.remove or removeIf.

Q15) What is the difference between Arrays.asList and List.of?

Answer Arrays.asList returns a fixed-size list backed by the array that allows set and nulls. List.of returns an immutable list that rejects set, add, remove, and nulls.

Q16) How do you convert an ArrayList to an array?

Answer Use list.toArray(new String[0]) for objects. For int[], use list.stream().mapToInt(Integer::intValue).toArray().

Q17) How do you remove duplicates from an ArrayList while keeping order?

Answer Copy it through a LinkedHashSet: new ArrayList<>(new LinkedHashSet<>(list)), or use list.stream().distinct().toList().

Q18) How do you sort an ArrayList of custom objects?

Answer Implement Comparable in the class and call Collections.sort, or pass a Comparator such as Comparator.comparing(Employee::getSalary) to list.sort.

Q19) What is subList and what is the risk?

Answer subList returns a view of a range. Changes write through to the original list, and structural changes to the original make the view throw ConcurrentModificationException.

Q20) What is the RandomAccess interface?

Answer A marker interface that tells algorithms index access is fast. ArrayList implements it; LinkedList does not, so utilities like binarySearch choose a different strategy.

L4

Simple Programs

Student marks manager

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

public class MarksManager {
    record Student(String name, int marks) { }

    public static void main(String[] args) {
        List<Student> cls = new ArrayList<>(List.of(
            new Student("Asha", 88), new Student("Ravi", 45), new Student("Kiran", 92),
            new Student("Meena", 67), new Student("John", 30)
        ));

        cls.set(1, new Student("Ravi", 55));                  // re-evaluation: update marks
        cls.removeIf(s -> s.name().equals("John"));           // transferred out

        int total = 0;
        Student topper = cls.get(0);
        List<String> needHelp = new ArrayList<>();
        for (Student s : cls) {
            total += s.marks();
            if (s.marks() > topper.marks()) topper = s;
            if (s.marks() < 60) needHelp.add(s.name());
        }

        System.out.printf("Students: %d, average: %.2f%n", cls.size(), (double) total / cls.size());
        System.out.println("Topper: " + topper.name() + " (" + topper.marks() + ")");
        System.out.println("Extra classes for: " + needHelp);
        // Students: 4, average: 75.50 / Topper: Kiran (92) / Extra classes for: [Ravi]
    }
}

Shopping cart with quantities

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

public class ShoppingCart {
    record Item(String name, int price, int qty) {
        int total() { return price * qty; }
    }

    private final List<Item> items = new ArrayList<>();

    void add(String name, int price, int qty) {
        for (int i = 0; i < items.size(); i++) {
            Item it = items.get(i);
            if (it.name().equals(name)) {                    // already in cart: increase quantity
                items.set(i, new Item(name, price, it.qty() + qty));
                return;
            }
        }
        items.add(new Item(name, price, qty));
    }

    void remove(String name) {
        items.removeIf(it -> it.name().equals(name));
    }

    void printBill() {
        int sum = 0;
        for (Item it : items) {
            System.out.printf("%-10s %2d x %4d = %5d%n", it.name(), it.qty(), it.price(), it.total());
            sum += it.total();
        }
        System.out.println("Grand total: Rs." + sum);
    }

    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        cart.add("Rice 5kg", 450, 1);
        cart.add("Milk", 30, 2);
        cart.add("Soap", 40, 3);
        cart.add("Milk", 30, 1);          // quantity becomes 3
        cart.remove("Soap");
        cart.printBill();                 // Rice 450 + Milk 90 = Rs.540
    }
}

Remove duplicates while keeping order

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

public class RemoveDuplicates {
    public static void main(String[] args) {
        List<String> signups = new ArrayList<>(List.of("asha", "ravi", "asha", "kiran", "ravi", "meena"));

        List<String> manual = new ArrayList<>();
        for (String s : signups) {
            if (!manual.contains(s)) manual.add(s);          // simple, O(n^2): fine for small lists
        }

        List<String> fast = new ArrayList<>(new LinkedHashSet<>(signups));   // O(n), keeps order
        List<String> viaStream = signups.stream().distinct().toList();

        System.out.println(manual);      // [asha, ravi, kiran, meena]
        System.out.println(fast);        // [asha, ravi, kiran, meena]
        System.out.println(viaStream);   // [asha, ravi, kiran, meena]
    }
}

Mutual friends and friend suggestions

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

public class FriendSuggestions {
    public static void main(String[] args) {
        List<String> ashaFriends = new ArrayList<>(List.of("Ravi", "Kiran", "Meena", "John"));
        List<String> raviFriends = new ArrayList<>(List.of("Asha", "Kiran", "John", "Sita"));

        List<String> mutual = new ArrayList<>(ashaFriends);
        mutual.retainAll(raviFriends);                    // intersection
        System.out.println("Mutual friends: " + mutual);  // [Kiran, John]

        List<String> suggestForRavi = new ArrayList<>(ashaFriends);
        suggestForRavi.removeAll(raviFriends);            // difference
        suggestForRavi.remove("Ravi");                    // not himself
        System.out.println("Suggest to Ravi: " + suggestForRavi);   // [Meena]

        List<String> everyone = new ArrayList<>(ashaFriends);
        for (String f : raviFriends) {                    // union without duplicates
            if (!everyone.contains(f)) everyone.add(f);
        }
        System.out.println("Party invite list: " + everyone);
        // [Ravi, Kiran, Meena, John, Asha, Sita]
    }
}

Playlist: reverse, rotate, and swap

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

public class PlaylistTools {
    public static void main(String[] args) {
        List<String> playlist = new ArrayList<>(List.of("S1", "S2", "S3", "S4", "S5"));

        for (int i = 0, j = playlist.size() - 1; i < j; i++, j--) {   // manual two-pointer reverse
            String tmp = playlist.get(i);
            playlist.set(i, playlist.get(j));
            playlist.set(j, tmp);
        }
        System.out.println(playlist);           // [S5, S4, S3, S2, S1]

        Collections.reverse(playlist);          // back to [S1, S2, S3, S4, S5]
        Collections.rotate(playlist, 2);        // last two songs move to the front
        System.out.println(playlist);           // [S4, S5, S1, S2, S3]

        Collections.swap(playlist, 0, 4);
        System.out.println(playlist);           // [S3, S5, S1, S2, S4]
    }
}

Cinema hall seating with a 2D ArrayList

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

public class CinemaSeats {
    public static void main(String[] args) {
        List<List<String>> hall = new ArrayList<>();
        int[] seatsPerRow = { 4, 5, 6 };                       // rows can have different sizes

        for (int r = 0; r < seatsPerRow.length; r++) {
            List<String> row = new ArrayList<>();
            for (int s = 1; s <= seatsPerRow[r]; s++) {
                row.add("" + (char) ('A' + r) + s);
            }
            hall.add(row);
        }

        hall.get(1).set(2, "XX");                               // seat B3 booked
        hall.get(2).add("C7");                                  // extra seat added to row C

        for (List<String> row : hall) {
            System.out.println(row);
        }
        // [A1, A2, A3, A4]
        // [B1, B2, XX, B4, B5]
        // [C1, C2, C3, C4, C5, C6, C7]
    }
}

Highest and second highest score

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

public class SecondHighest {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(List.of(72, 95, 88, 95, 60, 88));

        int highest = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        for (int s : scores) {
            if (s > highest) {
                second = highest;
                highest = s;
            } else if (s > second && s != highest) {
                second = s;
            }
        }
        System.out.println("Highest: " + highest + ", second highest: " + second);   // 95, 88
        System.out.println("95 scored by " + Collections.frequency(scores, 95) + " students");   // 2
    }
}
L5

Problem Solving Tricks

  • Declare as List<T>, create as new ArrayList<>().
  • Pre-size with new ArrayList<>(expected) when you know the size.
  • On List<Integer>, remove(1) removes index 1; use remove(Integer.valueOf(1)) for the value.
  • Never add or remove inside a for-each loop; use removeIf or Iterator.remove().
  • Remove in a loop? Go backwards with the index: for (int i = list.size() - 1; i >= 0; i--).
  • Arrays.asList is fixed-size; wrap it in new ArrayList<>(...) to add or remove.
  • Compare Integer elements with equals, not ==.
  • Override equals and hashCode in custom classes so contains and remove(Object) work.
  • subList is a view; copy it with new ArrayList<>(list.subList(a, b)) if you need to keep it.
  • Use List.of(...) for constant lists and ArrayDeque when you keep removing from the front.
L6

Practice Programs List

  1. Create a to-do list, add five tasks, insert an urgent task at index 0, and print the first and last tasks.
  2. Store ten numbers and print their sum, average, maximum, and minimum.
  3. Show remove(1) vs remove(Integer.valueOf(1)) on a List<Integer>.
  4. Remove all even numbers in three ways: backward index loop, Iterator, and removeIf.
  5. Find the index of the first and last occurrence of a name using indexOf and lastIndexOf.
  6. Sort a list of names A to Z, Z to A, case-insensitively, and by length.
  7. Create an ArrayList<Employee>, give everyone a 10% raise, and print them sorted by salary.
  8. Convert a String[] to an ArrayList, add an element, and convert it back to an array.
  9. Demonstrate that Arrays.asList throws on add but allows set.
  10. Remove duplicates from a list while keeping the original order.
  11. Find mutual friends of two people with retainAll.
  12. Reverse an ArrayList manually with two pointers, without Collections.reverse.
  13. Build a 2D ArrayList for a classroom with rows of different sizes.
  14. Trigger ConcurrentModificationException by removing inside a for-each, then fix it.