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 ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

121 · 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 sequence that allows duplicates and index access. Set holds unique elements. Queue orders elements for processing (usually FIFO). Map stores key-to-value pairs. Map is not a Collection because it deals with pairs, not single elements.

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

They operate on whole collections at once: addAll adds everything from another collection (union), removeAll deletes everything also in another (difference), retainAll keeps only what's in another (intersection), containsAll checks if all elements are present (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; the modern idiom 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 is split out so anything traversable - not just collections - can be used in for-each (streams sources, lazy/infinite sequences, custom cursors). Map is kept separate because it stores pairs, not single elements, so it can't honestly implement the single-element Collection contract.

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. Changes to the view show up in the original list and vice versa. The range is from inclusive to to exclusive.

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 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

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

Explain the equals/hashCode contract and why violating it breaks a HashSet.

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

If two objects are equal by equals(), they must return the same hashCode(). If you break this, a HashSet can store duplicates or fail to find elements you put in.

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 is the cheapest way to read both key and value together.

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 — without changing the map. putIfAbsent(key, value) only stores the value if the key is missing (or maps to null) and returns the previous value, leaving an existing value untouched.

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 that is thread-safe because every method is synchronized, 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

The Queue interface offers two families of operations for inserting, removing, and inspecting elements. What are they, and how do they differ in behavior on failure?

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

Queue has two sets of methods. add/remove/element throw an exception when they can't do the operation. offer/poll/peek instead return a special value (false or null) and don't throw.

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
~10 s

Iterating (for-each, iterator, toArray, toString) walks the internal heap array, which is only partially ordered - just the head is guaranteed smallest. Only repeatedly calling poll() gives elements in true sorted order.

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

It's an error Java throws when you change a collection's structure (add or remove items) while looping over it with a for-each loop or iterator. The classic case: removing an element from a list inside a for-each loop.

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 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 throws an error. Instead use removeIf() with a condition, or use an explicit Iterator and call iterator.remove(). You can also loop over a copy of the list and remove from the original.

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

It's an IllegalArgumentException Java throws when your comparator gives inconsistent answers - for example saying 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

They are static methods added in Java 9 that build small, unchangeable collections in one line, like List.of(1, 2, 3). The returned collection cannot be added to, removed from, or modified.

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
~10 s

Collections.sort(list) orders a list ascending, either by the elements' natural order or by a Comparator you pass. 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

The factory methods create a brand-new collection that is truly immutable and copies nothing live. 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
~10 s

Collections.emptyList() gives you a shared, immutable empty list, 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 keys are spread across buckets by their hash. In the worst case (many collisions) they can degrade to O(n), or O(log n) since Java 8 when a bucket converts to a balanced tree.

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 only 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