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.
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?
ArrayListis a resizable array injava.util. It implements theListinterface, 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
| Feature | Meaning |
|---|---|
| Dynamic size | Grows automatically (about 1.5 times) when full |
| Ordered | Keeps elements in insertion order |
| Index based | get(i) and set(i, e) are fast; index starts at 0 |
| Duplicates | Allowed |
| null | Allowed, even many times |
| Objects only | Primitives are auto-boxed: int becomes Integer |
| Not synchronized | Not thread-safe without extra locking |
| Fail-fast iterator | Throws ConcurrentModificationException if changed during a for-each |
| Interfaces | List, RandomAccess, Cloneable, Serializable |
| Backing store | An 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 / way | Meaning | Example |
|---|---|---|
new ArrayList<>() | Empty list; capacity 10 is allocated on the first add | List<String> names = new ArrayList<>(); |
new ArrayList<>(int capacity) | Empty list with room for that many elements | new ArrayList<>(500) |
new ArrayList<>(Collection c) | Copy of another collection, fully modifiable | new 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
| Point | Array | ArrayList |
|---|---|---|
| Size | Fixed at creation | Grows and shrinks automatically |
| Syntax | int[] a = new int[5]; | List<Integer> a = new ArrayList<>(); |
| Primitives | Yes: int[] | No: uses wrappers like Integer |
| Length / size | a.length (field) | list.size() (method) |
| Access | a[i] | list.get(i) |
| Change element | a[i] = x | list.set(i, x) |
| Add / remove | Not possible (create a new array) | add, remove, removeIf, clear |
| Built-in helpers | Through Arrays class | Many methods plus Collections |
| Speed / memory | Slightly faster, less memory | Small overhead, much more convenient |
| Multi-dimensional | int[][] | List<List<Integer>> |
| Real life | Egg tray with 12 fixed slots | Stretchable shopping bag |
Important ArrayList methods
| Method | What it does | Example |
|---|---|---|
add(e) | Adds at the end | cart.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 collection | cart.addAll(List.of("Eggs", "Tea")) |
get(i) | Element at index i | cart.get(2) |
set(i, e) | Replaces the element at index i; returns the old one | cart.set(1, "Butter") |
remove(int i) | Removes by index | cart.remove(0) |
remove(Object o) | Removes the first matching element | cart.remove("Milk") |
removeIf(predicate) | Removes all elements matching a condition | cart.removeIf(x -> x.isEmpty()) |
removeAll(c) / retainAll(c) | Difference / intersection with another collection | cart.removeAll(outOfStock) |
contains(o) | True if the element exists | cart.contains("Tea") |
indexOf(o) / lastIndexOf(o) | First / last position, or -1 | cart.indexOf("Tea") |
size() / isEmpty() | Count / empty check | cart.size() |
clear() | Removes all elements | cart.clear() |
sort(comparator) | Sorts the list (null = natural order) | cart.sort(Comparator.naturalOrder()) |
replaceAll(operator) | Transforms every element | cart.replaceAll(String::toUpperCase) |
forEach(action) | Runs an action for each element | cart.forEach(System.out::println) |
subList(from, to) | View of a range (to excluded) | cart.subList(0, 3) |
toArray(new T[0]) | Copies into an array | cart.toArray(new String[0]) |
iterator() / listIterator() | Cursor for safe removal or two-way looping | cart.iterator() |
ensureCapacity(n) / trimToSize() | Reserve space / release unused space | list.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 andset(i, e)replaces. Valid indexes are 0 tosize() - 1; anything else throwsIndexOutOfBoundsException.- 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;removeIfdeletes everything matching a condition;clearempties the list.- Trap: on
List<Integer>,remove(1)removes the element at index 1, not the value 1. Useremove(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, andlastIndexOfscan from the start, so they take O(n) time. They useequals()to compare.- For a sorted list,
Collections.binarySearchfinds 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,
Iteratorto remove while looping,ListIteratorto replace or go backwards, andforEachfor 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)orlist.sort(null)sorts in natural order (numbers ascending, strings A to Z with capitals first).- Pass a
Comparatorfor other orders:Comparator.reverseOrder(),String.CASE_INSENSITIVE_ORDER, orComparator.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
EmployeeorProduct. OverridetoString()for readable printing. - Override
equals()(andhashCode()) so thatcontains,indexOf, andremove(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:setworks (and changes the array), butaddandremovethrowUnsupportedOperationException.- Wrap it for a real, resizable copy:
new ArrayList<>(Arrays.asList(array)). - Go back with
list.toArray(new String[0]). Forint[], use streams withboxed()andmapToInt.
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)boxes5into anInteger;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
nullelement into anintthrowsNullPointerException.
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
| Point | ArrayList | LinkedList |
|---|---|---|
| Structure | Dynamic array | Doubly linked nodes |
get(i) / set(i) | O(1) | O(n) |
add at end | Amortized O(1) | O(1) |
add / remove at front | O(n) (shifts elements) | O(1) |
| Insert in the middle | O(n) shifting | O(n) to find the spot, then O(1) |
| Memory | Compact array | Extra node objects with two pointers each |
| CPU cache locality | Excellent | Poor |
Implements Deque | No | Yes |
RandomAccess marker | Yes | No |
| Real life | Numbered seats in a theatre | A treasure hunt where each clue points to the next |
| Default choice | Yes | Rarely (use ArrayDeque for queues) |
Advanced — ArrayList
How ArrayList works internally
- Inside is an
Object[] elementDataand anint size.sizeis how many elements you stored; capacity is the length of the internal array. - A new
ArrayList<>()starts with a shared empty array. The firstaddallocates capacity 10. - When the array is full,
grow()creates a bigger array ofold + old / 2(about 1.5 times) and copies elements withArrays.copyOf. Growth sequence: 10, 15, 22, 33, 49, 73, 109, ... - Removing does not shrink the array. Call
trimToSize()to release unused space, orensureCapacity(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
| Operation | Time | Why |
|---|---|---|
get(i), set(i, e) | O(1) | Direct array index |
add(e) at end | Amortized O(1) | Occasional resize copies all elements |
add(i, e) in the middle or front | O(n) | Shifts later elements right |
remove(i) in the middle or front | O(n) | Shifts later elements left |
remove(size() - 1) last element | O(1) | Nothing to shift |
contains, indexOf, remove(Object) | O(n) | Linear scan with equals |
removeIf(predicate) | O(n) | Single pass, compacts once |
sort | O(n log n) | TimSort |
Collections.binarySearch on a sorted list | O(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 throwsConcurrentModificationExceptionif the list changes behind its back. - Calling
list.removeorlist.addinside 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
| Point | new ArrayList<>(...) | Arrays.asList(...) | List.of(...) |
|---|---|---|---|
| add / remove | Yes | No: UnsupportedOperationException | No: UnsupportedOperationException |
| set | Yes | Yes (writes to the array) | No |
| null elements | Allowed | Allowed | Not allowed: NullPointerException |
| Backed by an array? | Own internal array | Yes, the array you passed | Own immutable storage |
| Java version | 1.2 | 1.2 | 9 |
| Use when | You need a normal, changeable list | Quick fixed-size view of an array | Constant data that never changes |
Differences between ArrayList, Vector, and CopyOnWriteArrayList
| Point | ArrayList | Vector | CopyOnWriteArrayList |
|---|---|---|---|
| Thread-safe | No | Yes (every method synchronized) | Yes (copy on every write) |
| Speed (single thread) | Fastest | Slower (locking) | Slow writes, fast reads |
| Growth | About 1.5 times | 2 times | New array on every write |
| Iterator | Fail-fast | Fail-fast | Snapshot, never throws CME |
| Legacy? | No | Yes (Java 1.0) | No (java.util.concurrent) |
| Use when | Default list | Old code only | Many readers, rare writers (listeners) |
ArrayList and threads
ArrayListis not thread-safe. Two threads adding at once can lose elements or throwArrayIndexOutOfBoundsException.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 aBlockingQueueinstead 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(), andreversed()toArrayListthroughSequencedCollection. - 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
| Do | Do not |
|---|---|
Pre-size with new ArrayList<>(expected) for big lists | Let a million-element list resize 30 times |
Use removeIf for bulk removal | Call remove(i) in a forward loop (skips elements, O(n²)) |
Use ArrayDeque when you add or remove at the front often | Use list.remove(0) as a queue |
Use a HashSet for frequent contains checks | Call list.contains inside a big loop |
Declare as List<T> | Expose ArrayList<T> in method signatures |
Use List.of / List.copyOf for constants | Return internal mutable lists from getters |
Use subList(a, b).clear() to delete a range | Remove a range one element at a time |
Compare elements with equals | Compare Integer elements with == |
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.
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
}
} Problem Solving Tricks
- Declare as
List<T>, create asnew ArrayList<>(). - Pre-size with
new ArrayList<>(expected)when you know the size. - On
List<Integer>,remove(1)removes index 1; useremove(Integer.valueOf(1))for the value. - Never add or remove inside a for-each loop; use
removeIforIterator.remove(). - Remove in a loop? Go backwards with the index:
for (int i = list.size() - 1; i >= 0; i--). Arrays.asListis fixed-size; wrap it innew ArrayList<>(...)to add or remove.- Compare
Integerelements withequals, not==. - Override
equalsandhashCodein custom classes socontainsandremove(Object)work. subListis a view; copy it withnew ArrayList<>(list.subList(a, b))if you need to keep it.- Use
List.of(...)for constant lists andArrayDequewhen you keep removing from the front.
Practice Programs List
- Create a to-do list, add five tasks, insert an urgent task at index 0, and print the first and last tasks.
- Store ten numbers and print their sum, average, maximum, and minimum.
- Show
remove(1)vsremove(Integer.valueOf(1))on aList<Integer>. - Remove all even numbers in three ways: backward index loop, Iterator, and
removeIf. - Find the index of the first and last occurrence of a name using
indexOfandlastIndexOf. - Sort a list of names A to Z, Z to A, case-insensitively, and by length.
- Create an
ArrayList<Employee>, give everyone a 10% raise, and print them sorted by salary. - Convert a
String[]to an ArrayList, add an element, and convert it back to an array. - Demonstrate that
Arrays.asListthrows onaddbut allowsset. - Remove duplicates from a list while keeping the original order.
- Find mutual friends of two people with
retainAll. - Reverse an ArrayList manually with two pointers, without
Collections.reverse. - Build a 2D ArrayList for a classroom with rows of different sizes.
- Trigger
ConcurrentModificationExceptionby removing inside a for-each, then fix it.