Skip to content

Intermediate · The collections framework · topic 31 of 60 · 30 min

Collections overview and List

Explanation

The collections framework gives ready-made data structures behind common interfaces: List (ordered, allows duplicates), Set (no duplicates), Queue/Deque (processing order) and Map (key → value). ArrayList is the default List: fast random access, growing automatically. LinkedList is rarely better. List.of makes small unmodifiable lists. Never remove items inside a for-each loop; use removeIf or an Iterator.

Why a framework?

Arrays have a fixed size and few features. Almost every program needs growing lists, unique sets and lookups by key. Java's collections framework (in java.util) provides tested, fast implementations behind a few common interfaces, so code written against List works with any list.

output
Collection
├── List      (ordered, duplicates allowed)   → ArrayList, LinkedList
├── Set       (no duplicates)                 → HashSet, LinkedHashSet, TreeSet
└── Queue     (processing order)              → ArrayDeque, PriorityQueue, LinkedList
Map (separate: key → value)                   → HashMap, LinkedHashMap, TreeMap

ArrayList

java
List<String> cart = new ArrayList<>();
cart.add("Rice");                // append
cart.add("Dal");
cart.add(0, "Oil");              // insert at index 0: [Oil, Rice, Dal]
System.out.println(cart.get(1)); // Rice
cart.set(2, "Moong dal");        // replace
cart.remove("Rice");             // by value → [Oil, Moong dal]
System.out.println(cart.size() + " " + cart.contains("Oil"));   // 2 true
for (String item : cart) System.out.println(item);

ArrayList stores elements in an internal array that grows (roughly by half) when full. get(i) and set(i) are instant (O(1)); adding at the end is fast on average; inserting or removing in the middle shifts later elements (O(n)).

ArrayList versus LinkedList

OperationArrayListLinkedList
get(i)O(1) fastO(n) walks the chain
add at endO(1) amortisedO(1)
add/remove at the startO(n)O(1)
Memory per elementSmallLarger (node objects with links)
Use whenAlmost alwaysRarely; ArrayDeque is usually better for queues

Immutable lists

java
List<String> zones = List.of("North", "South", "East", "West");   // unmodifiable (Java 9+)
// zones.add("Central");     // UnsupportedOperationException at run time
List<String> copy = new ArrayList<>(zones);                        // a modifiable copy
List.of does not allow null elements.

Removing while iterating

java
List<Integer> amounts = new ArrayList<>(List.of(100, -5, 250, 0, 80));
// for (Integer a : amounts) if (a <= 0) amounts.remove(a);   // ConcurrentModificationException
amounts.removeIf(a -> a <= 0);                                // Java 8+: [100, 250, 80]

Iterator<Integer> it = amounts.iterator();                    // the classic way
while (it.hasNext()) if (it.next() > 200) it.remove();        // [100, 80]
Careful: list.remove(1) on a List<Integer> removes the element at INDEX 1, not the value 1, because remove(int index) is chosen over remove(Object). To remove the value, write list.remove(Integer.valueOf(1)). This trap appears in interviews and real bugs.
Think of it like this: An ArrayList is like seats in a cinema row: you can jump straight to seat 7, but inserting a new person in the middle makes everyone after them shift one seat. A LinkedList is like people holding hands in a chain: easy to add someone anywhere you already are, but to reach the 7th person you must walk along the chain.
Tip: Declare variables with the interface type (List<String> cart = new ArrayList<>()) and pass List to methods. Your code then works with any list implementation.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Collections overview and List · 1/6

Collections and List

In this lesson you will meet the collections framework and use List.

Prefer a video by a teacher? Find free videos on “java collections framework arraylist vs linkedlist tutorial” on YouTube ↗

In real life: A delivery route list

A delivery app keeps the day's drop-off addresses in an ArrayList. The rider sees them in order; cancelled orders are removed with removeIf, and an urgent order is inserted at the front.

java
List<String> stops = new ArrayList<>(List.of("A-12 Kothrud", "C-4 Aundh", "B-7 Baner"));
stops.removeIf(s -> s.startsWith("C-"));     // order C-4 was cancelled
stops.add(0, "URGENT: D-1 Wakad");
System.out.println(stops);   // [URGENT: D-1 Wakad, A-12 Kothrud, B-7 Baner]

Practice (0/3 done)

Task 1 · Question

What does this print? List<Integer> l = new ArrayList<>(List.of(5, 7, 1)); l.remove(1); System.out.println(l);

Task 2 · Question

What happens? List<String> l = List.of("a", "b"); l.add("c");

Task 3 · Practice

Write a program that stores 8 order amounts in an ArrayList<Integer>, removes the refunded ones (amounts below 0) with removeIf, inserts a new order at the front, and prints the size, the total and the list. Then show the remove(int) versus remove(Object) trap with a comment.

Quick quiz

Question 1

1.Which interface does NOT extend Collection?

Question 2

2.Which is fastest for get(500000)?

Question 3

3.Removing elements inside a for-each loop over an ArrayList usually throws…

Question 4

4.Does a List allow duplicates?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which interface does NOT extend Collection?

Answer: Map

Map is a separate hierarchy.

Which is fastest for get(500000)?

Answer: ArrayList

ArrayList has O(1) random access.

Removing elements inside a for-each loop over an ArrayList usually throws…

Answer: ConcurrentModificationException

The iterator detects the structural change.

Does a List allow duplicates?

Answer: Yes

Lists keep every element in order, duplicates included.

How do you make an empty set?Related

Answer: set()

{} makes an empty dict. The only way to make an empty set is set().

From Sets: each item only once

What does it->first give for a std::map iterator?Related

Answer: The key

Map elements are pairs: first is the key, second is the value.

From Iterators: the glue between containers and algorithms

Which deque operation is NOT O(1)?Related

Answer: q[len(q) // 2]

A deque is a linked structure of blocks: both ends are O(1), the middle is O(n).

From Queues and deques

Why must a HashMap key override both equals and hashCode?Related

Answer: So equal keys land in the same bucket and are found

The contract keeps lookups correct.

From Java interview questions

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “The collections framework” before its exam: Sets: HashSet, LinkedHashSet and TreeSet, Maps: HashMap, LinkedHashMap and TreeMap, Sorting with Comparable and Comparator, Queues, stacks and priority queues.
  2. Module 7 exam: The collections framework · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Lambdas, streams and files. 60 topics left in the course before the final exam.

← Previous: Avoiding NullPointerException