skip to content

Collections Framework

The Collections Framework: the interface hierarchy, the List, Set, Map and Queue implementations and their internals, iteration, ordering, utilities, and the cost profiles that drive selection. After equals/hashCode, this is the most reliably examined Java library area.

part ofJavaread it →
on this pageshow

explore

questions

128 · 9 sections

What is the Iterable interface in Java, and how does it enable the for-each loop?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Iterable is an interface with one main method, iterator(), that returns an Iterator. Any class that implements Iterable can be used in a for-each loop, because the compiler turns the loop into calls to iterator(), hasNext(), and next().

open as a page

Distinguish the List, Set, Queue, and Map interfaces in the Java Collections Framework. Which is not a Collection, and why?

level: juniorimportance: must knowfreq 80%
basics
~20 s

List is an ordered, indexed sequence that typically allows duplicates. Set holds no duplicates. Queue orders elements for processing, usually FIFO. Map stores key-value pairs and is not a Collection: a mere collection of pairs could not look up by key.

open as a page

What are the Collection bulk operations (addAll, removeAll, retainAll, containsAll, clear), and what set-like semantics do they implement?

level: middleimportance: should knowfreq 60%
basics
~20 s

Bulk operations act on many elements at once: addAll adds another collection's elements (union on a Set), removeAll deletes those also in it (difference), retainAll keeps only those (intersection), containsAll tests for a subset, and clear empties the collection.

open as a page

Explain Collection.toArray() and toArray(T[]). Why does the no-arg version return Object[], and what is the correct way to call the typed overload?

level: middleimportance: should knowfreq 55%
basics
~20 s

toArray() returns an Object[] because the collection doesn't know its element type at runtime (type erasure). toArray(T[]) returns a properly typed array; a common call is list.toArray(new String[0]), and Java 11 added the cleaner list.toArray(String[]::new).

open as a page

From an API-design standpoint, why is Iterable separate from Collection, and why did the designers keep Map outside the Collection hierarchy? What does this teach about interface segregation?

level: principalimportance: nice to knowfreq 30%
basics
~20 s

Iterable carries only traversal, so non-collections such as Path, ServiceLoader and DirectoryStream work in for-each without a Collection's other methods. Map stays separate by design: as a mere collection of pairs it could not look up or delete by key.

open as a page

What is the fundamental difference between ArrayList and LinkedList in Java, and how does it affect their performance characteristics?

level: juniorimportance: must knowfreq 85%
basics
~20 s

ArrayList stores elements in a resizable array, so reading any element by index is instant. LinkedList stores elements as separate nodes connected by links, so reading by index means walking the chain. ArrayList is faster for most uses.

open as a page

What is an ArrayList in Java, and how does it store its elements?

level: juniorimportance: must knowfreq 85%
basics
~10 s

An ArrayList is a resizable list backed by an array. You can add items without picking a size up front, and you read any item by its position (index) quickly.

open as a page

What is the internal data structure of java.util.LinkedList, and how does it differ from ArrayList?

level: juniorimportance: must knowfreq 78%
basics
~20 s

LinkedList stores each element in a separate node that points to the next and previous nodes (a doubly-linked list). ArrayList stores elements in a single backing array. So LinkedList chases pointers; ArrayList uses index math.

open as a page

What does List.subList(from, to) return, and how does it relate to the original list?

level: juniorimportance: must knowfreq 55%
basics
~20 s

subList(from, to) returns a view of part of the original list, not a copy, from inclusive to to exclusive. Changes to the view reach the original, and element updates in the original reach the view.

open as a page

What happens if you modify an ArrayList while iterating over it, and how do you handle it correctly?

level: middleimportance: must knowfreq 78%
basics
~10 s

Changing an ArrayList's size while looping over it with its iterator usually throws ConcurrentModificationException. To remove during iteration, use the iterator's own remove() method, or skip the loop and use removeIf.

open as a page

What is a HashSet in Java and what guarantees does it provide about element ordering and uniqueness?

level: juniorimportance: must knowfreq 78%
basics
~10 s

A HashSet is a collection that stores unique elements with no duplicates. It does not keep elements in any particular order, and you cannot rely on the order when you iterate over it.

open as a page

What is a Set in Java, and how does it decide that two elements are duplicates?

level: juniorimportance: must knowfreq 78%
basics
~10 s

A Set is a collection that holds no duplicate elements. When you add an element, the Set checks the ones already stored; if an equal one exists, the new element is not added.

open as a page

What is a TreeSet in Java, and how does it differ from a HashSet?

level: juniorimportance: must knowfreq 75%
basics
~10 s

A TreeSet is a Set that keeps its elements automatically sorted. A HashSet stores elements in no particular order but is faster. Use TreeSet when you need the elements in order.

open as a page

How does a Java HashSet work internally: what does its backing HashMap store, what is PRESENT for, and what does add() return?

level: middleimportance: must knowfreq 68%
basics
~20 s

HashSet delegates to one HashMap field: elements are its keys and every value is one shared PRESENT object. add() calls put and returns true only when put finds no earlier mapping, so a duplicate leaves the set unchanged.

open as a page

What is the difference between HashSet and LinkedHashSet, and when would you choose one over the other?

level: middleimportance: must knowfreq 70%
basics
~10 s

Both store unique elements. HashSet has no defined iteration order, while LinkedHashSet remembers the order you added items and iterates them in that insertion order. Choose LinkedHashSet when order matters.

open as a page

How does a Java HashMap store key-value pairs internally, and how does it find a value by key?

level: juniorimportance: must knowfreq 90%
basics
~20 s

A HashMap keeps an array of buckets. It turns each key into a number (a hash), uses that number to pick a bucket, and stores the key and value there. To get a value it hashes the key again, jumps to the same bucket, and compares keys with equals to find the match.

open as a page

What is LinkedHashMap and how does its iteration order differ from HashMap?

level: juniorimportance: must knowfreq 70%
basics
~10 s

LinkedHashMap is a HashMap that also remembers the order you put entries in, so iterating returns them in insertion order. A plain HashMap gives no order guarantee and can appear random.

open as a page

What is Map.Entry and how do you use it to iterate over a Map's key-value pairs?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Map.Entry represents one key-value pair in a Map. You get all pairs with map.entrySet() and loop over them, calling getKey() and getValue() on each entry. This avoids the extra lookup that keySet() plus get() makes for each key.

open as a page

How do getOrDefault and putIfAbsent simplify common Map access patterns, and how do they differ?

level: juniorimportance: must knowfreq 68%
basics
~20 s

getOrDefault(key, fallback) returns the value if the key exists, otherwise the fallback, and inserts nothing. putIfAbsent(key, value) stores the value only if the key is missing or maps to null, and returns the previous value.

open as a page

What is Hashtable, how does it differ from HashMap, and why is it considered a legacy class?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Hashtable is an old key-value map whose get, put and similar calls share one lock, so each is thread-safe, and it refuses null keys and null values. HashMap is newer, faster, allows one null key and null values, but is not thread-safe.

open as a page

What is a PriorityQueue in Java and how do you get elements out in priority order?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A PriorityQueue is a queue where the smallest element (by natural order or a Comparator) always comes out first. You add with offer/add and remove the highest-priority element with poll. peek looks at the head without removing it.

open as a page

What is Java's Queue interface, and how do its two families of insert, remove and inspect operations differ on failure?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Queue is the java.util interface for holding elements before processing, typically FIFO. add/remove/element throw when they cannot act; offer/poll/peek report a full or empty queue by returning false or null.

open as a page

Why is iterating over a PriorityQueue not the same as getting elements in sorted order?

level: middleimportance: must knowfreq 62%
basics
~20 s

Iterating (for-each, iterator, toArray, toString) walks the internal heap array, which is only partially ordered - just the head is guaranteed smallest. Repeatedly calling poll() drains them in priority order; sorting a copy leaves the queue intact.

open as a page

What is a Deque, and how do its head and tail operations let it act as both a queue and a stack?

level: middleimportance: must knowfreq 65%
basics
~20 s

A Deque (double-ended queue) lets you add and remove from both ends. You can use it FIFO like a queue (add at one end, remove from the other) or LIFO like a stack (add and remove from the same end).

open as a page

How do you control PriorityQueue ordering (e.g. build a max-heap or order by an object field), and what must the Comparator guarantee?

level: middleimportance: should knowfreq 58%
basics
~10 s

Pass a Comparator to the constructor: PriorityQueue<>(Comparator.reverseOrder()) for a max-heap, or Comparator.comparingInt(Task::getPriority) to order by a field. Without one it uses the element's natural ordering, so the type must be Comparable.

open as a page

What is a ConcurrentModificationException, and when does it typically occur?

level: juniorimportance: must knowfreq 78%
basics
~20 s

ConcurrentModificationException is the unchecked exception a fail-fast iterator throws, on a best-effort basis, when its collection is structurally modified outside the iterator during a loop. The classic case is list.remove(x) inside a for-each, with no threads involved.

open as a page

What is the Iterator interface in Java, and what are its core methods?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Iterator is an object that walks through a collection one element at a time. You call hasNext() to check if more elements remain, next() to get the next one, and remove() to delete the last element returned.

open as a page

How does a fail-fast iterator in java.util, such as ArrayList's, detect concurrent modification internally?

level: middleimportance: must knowfreq 62%
basics
~20 s

The collection keeps a counter called modCount that goes up every time you add or remove an element. When you make an iterator, it remembers that number. On each next() it compares them; if they differ, the collection changed behind its back, so it throws.

open as a page

You need to remove elements from a List while iterating it. What are the correct ways, and what are the pitfalls of each?

level: middleimportance: must knowfreq 70%
basics
~20 s

Don't call list.remove() inside a for-each loop: it usually throws ConcurrentModificationException and can silently skip an element. Use removeIf() with a condition, or an explicit Iterator and iterator.remove(). Looping over a copy and removing from the original also works.

open as a page

How do you safely remove elements from a collection while iterating over it, and why is collection.remove() inside a loop dangerous?

level: middleimportance: must knowfreq 80%
basics
~10 s

Use the iterator's own remove() method, not the collection's. Calling list.remove() while looping with a for-each usually throws ConcurrentModificationException because the collection changed behind the iterator's back.

open as a page

What is the Comparator interface in Java, and how does it differ from Comparable / natural ordering?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Comparator is an object that tells Java how to order two items. Comparable is built into a class (its natural order); Comparator is a separate, external rule you pass to sort, so you can sort the same objects many different ways.

open as a page

How does Comparator.comparing with a key extractor work, and why is it preferred over writing compare by hand?

level: middleimportance: must knowfreq 75%
basics
~20 s

Comparator.comparing takes a function that pulls a sort key out of each object (like person -> person.getAge()), and builds a comparator that orders objects by that key. It's shorter and less error-prone than writing compare yourself.

open as a page

How do you build a multi-level (tie-breaking) sort using thenComparing, and what determines the order of the chain?

level: middleimportance: must knowfreq 72%
basics
~20 s

thenComparing adds a backup rule used only when the first comparator says two items are equal. You chain them in priority order: first comparator is primary, the next breaks ties, and so on - like sorting by last name, then by first name.

open as a page

How do you sort a collection that may contain null elements (or null sort keys) safely with a Comparator?

level: seniorimportance: should knowfreq 58%
basics
~10 s

Most comparators throw NullPointerException on null. Wrap your comparator with Comparator.nullsFirst(...) or nullsLast(...) so nulls are placed at the start or end instead of crashing.

open as a page

What is the 'Comparison method violates its general contract!' exception, what causes it, and how do you fix it?

level: principalimportance: should knowfreq 42%
basics
~20 s

IllegalArgumentException that Java's object sort (TimSort) can throw when it detects a comparator giving inconsistent answers, such as a < b, b < c, but a > c. The fix is to make the comparator's logic consistent (transitive and sign-symmetric).

open as a page

What is the java.util.Collections class, and how does it differ from the Collection interface?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Collection (no 's') is the interface that lists and sets implement. Collections (with 's') is a helper class full of static methods like sort, reverse, and emptyList that operate on those collections.

open as a page

What are the Java 9+ List.of, Set.of, and Map.of factory methods, and why were they introduced?

level: juniorimportance: must knowfreq 72%
basics
~10 s

List.of, Set.of and Map.of are static methods, added in Java 9, that build small unmodifiable collections in one expression, like List.of(1, 2, 3). Adding to, removing from or replacing in the result throws UnsupportedOperationException.

open as a page

How do Collections.sort and Collections.binarySearch work, and what are their requirements and complexity?

level: middleimportance: must knowfreq 65%
basics
~20 s

Collections.sort(list) orders a list in place, ascending by the elements' natural order or in the order a Comparator you pass defines. Collections.binarySearch(list, key) finds an element quickly, but only works if the list is already sorted.

open as a page

How do List.of / Set.of / Map.of differ from Collections.unmodifiableList / unmodifiableSet / unmodifiableMap?

level: middleimportance: must knowfreq 74%
basics
~20 s

List.of, Set.of and Map.of build a self-contained unmodifiable collection with no backing collection to change. The Collections.unmodifiable* methods only wrap an existing collection in a read-only view, so if the original changes, the view changes too.

open as a page

What are the Collections.emptyList and singletonList factories, and why are they useful?

level: juniorimportance: should knowfreq 45%
basics
~20 s

Collections.emptyList() gives you an immutable empty list, which the JDK reuses, and singletonList(x) gives an immutable one-element list. They are handy lightweight return values when you'd otherwise create a tiny list, and they can't be modified.

open as a page

What are the time complexities of common operations on ArrayList versus LinkedList, and when would you pick one over the other?

level: juniorimportance: must knowfreq 85%
basics
~20 s

ArrayList gives fast index access (O(1)) but slow inserts/removes in the middle (O(n)). LinkedList is slow to reach an element by index (O(n)) but fast at adding/removing at the ends (O(1)). Use ArrayList by default.

open as a page

What questions do you ask yourself to decide between a List, a Set, and a Map for a given task?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Use a List when you need ordered items and duplicates are fine. Use a Set when you need unique items only. Use a Map when you look things up by a key. Pick based on whether you have keys, need uniqueness, or care about order.

open as a page

What is the average and worst-case time complexity of HashMap get and put, and what makes the average case constant?

level: middleimportance: must knowfreq 80%
basics
~20 s

HashMap get and put are O(1) on average because hashes spread keys across buckets. Collisions degrade them to O(n), or O(log n) in a tree bin (since Java 8) when keys have distinct hashes or are Comparable.

open as a page

When would you choose ArrayList over LinkedList, and when (if ever) the reverse?

level: middleimportance: must knowfreq 78%
basics
~20 s

Use ArrayList almost always: it's a resizable array, fast for indexing and iteration, and cache-friendly. LinkedList mainly helps if you add/remove a lot at the very front or use it as a queue/deque — and even then ArrayDeque is usually better.

open as a page

How do you choose among HashMap, LinkedHashMap, and TreeMap (and the equivalent Set variants)?

level: middleimportance: must knowfreq 70%
basics
~20 s

HashMap is the default: fast, no ordering. LinkedHashMap keeps insertion order (or access order, for LRU caches). TreeMap keeps keys sorted and lets you do range queries, but it's a bit slower. Same idea for HashSet / LinkedHashSet / TreeSet.

open as a page