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 pageshowhide
explore
- Collection Hierarchy & Interfaces5 questions
- Iterable & Collection Interfaces5 questions
- List Implementations20 questions
- ArrayList6 questions
- LinkedList4 questions
- ArrayList vs LinkedList5 questions
- subList Views & indexOf5 questions
- Set Implementations16 questions
- HashSet & LinkedHashSet6 questions
- TreeSet & NavigableSet5 questions
- Set Uniqueness & CopyOnWriteArraySet5 questions
- Map Implementations29 questions
- HashMap6 questions
- LinkedHashMap & LRU6 questions
- TreeMap & NavigableMap6 questions
- Map.Entry & Default/Compute Methods6 questions
- Queue & Deque12 questions
- Queue, Deque & ArrayDeque6 questions
- PriorityQueue6 questions
- Iterators & Traversal16 questions
- Iterator & ListIterator6 questions
- Fail-Fast vs Fail-Safe Iterators5 questions
- Spliterator5 questions
- Ordering & Comparison5 questions
- Comparator & Composition5 questions
- Collections Utility & Factories10 questions
- Collections Static Utilities5 questions
- Immutable Factory Methods5 questions
- Performance & Selection15 questions
- Big-O of Collection Operations5 questions
- Capacity & Load Factor Tuning5 questions
- Choosing the Right Collection5 questions
questions
128 · 9 sectionsWhat is the Iterable interface in Java, and how does it enable the for-each loop?
basics
~20 sIterable 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().
Distinguish the List, Set, Queue, and Map interfaces in the Java Collections Framework. Which is not a Collection, and why?
basics
~20 sList 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.
What are the Collection bulk operations (addAll, removeAll, retainAll, containsAll, clear), and what set-like semantics do they implement?
basics
~20 sBulk 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.
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?
basics
~20 stoArray() 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).
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?
basics
~20 sIterable 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.
What is the fundamental difference between ArrayList and LinkedList in Java, and how does it affect their performance characteristics?
basics
~20 sArrayList 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.
What is an ArrayList in Java, and how does it store its elements?
basics
~10 sAn 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.
What is the internal data structure of java.util.LinkedList, and how does it differ from ArrayList?
basics
~20 sLinkedList 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.
What does List.subList(from, to) return, and how does it relate to the original list?
basics
~20 ssubList(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.
What happens if you modify an ArrayList while iterating over it, and how do you handle it correctly?
basics
~10 sChanging 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.
What is a HashSet in Java and what guarantees does it provide about element ordering and uniqueness?
basics
~10 sA 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.
What is a Set in Java, and how does it decide that two elements are duplicates?
basics
~10 sA 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.
What is a TreeSet in Java, and how does it differ from a HashSet?
basics
~10 sA 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.
How does a Java HashSet work internally: what does its backing HashMap store, what is PRESENT for, and what does add() return?
basics
~20 sHashSet 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.
What is the difference between HashSet and LinkedHashSet, and when would you choose one over the other?
basics
~10 sBoth 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.
How does a Java HashMap store key-value pairs internally, and how does it find a value by key?
basics
~20 sA 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.
What is LinkedHashMap and how does its iteration order differ from HashMap?
basics
~10 sLinkedHashMap 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.
What is Map.Entry and how do you use it to iterate over a Map's key-value pairs?
basics
~20 sMap.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.
How do getOrDefault and putIfAbsent simplify common Map access patterns, and how do they differ?
basics
~20 sgetOrDefault(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.
What is Hashtable, how does it differ from HashMap, and why is it considered a legacy class?
basics
~20 sHashtable 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.
What is a PriorityQueue in Java and how do you get elements out in priority order?
basics
~20 sA 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.
What is Java's Queue interface, and how do its two families of insert, remove and inspect operations differ on failure?
basics
~10 sQueue 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.
Why is iterating over a PriorityQueue not the same as getting elements in sorted order?
basics
~20 sIterating (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.
What is a Deque, and how do its head and tail operations let it act as both a queue and a stack?
basics
~20 sA 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).
How do you control PriorityQueue ordering (e.g. build a max-heap or order by an object field), and what must the Comparator guarantee?
basics
~10 sPass 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.
What is a ConcurrentModificationException, and when does it typically occur?
basics
~20 sConcurrentModificationException 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.
What is the Iterator interface in Java, and what are its core methods?
basics
~20 sIterator 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.
How does a fail-fast iterator in java.util, such as ArrayList's, detect concurrent modification internally?
basics
~20 sThe 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.
You need to remove elements from a List while iterating it. What are the correct ways, and what are the pitfalls of each?
basics
~20 sDon'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.
How do you safely remove elements from a collection while iterating over it, and why is collection.remove() inside a loop dangerous?
basics
~10 sUse 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.
What is the Comparator interface in Java, and how does it differ from Comparable / natural ordering?
basics
~20 sComparator 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.
How does Comparator.comparing with a key extractor work, and why is it preferred over writing compare by hand?
basics
~20 sComparator.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.
How do you build a multi-level (tie-breaking) sort using thenComparing, and what determines the order of the chain?
basics
~20 sthenComparing 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.
How do you sort a collection that may contain null elements (or null sort keys) safely with a Comparator?
basics
~10 sMost 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.
What is the 'Comparison method violates its general contract!' exception, what causes it, and how do you fix it?
basics
~20 sIllegalArgumentException 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).
What is the java.util.Collections class, and how does it differ from the Collection interface?
basics
~10 sCollection (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.
What are the Java 9+ List.of, Set.of, and Map.of factory methods, and why were they introduced?
basics
~10 sList.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.
How do Collections.sort and Collections.binarySearch work, and what are their requirements and complexity?
basics
~20 sCollections.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.
How do List.of / Set.of / Map.of differ from Collections.unmodifiableList / unmodifiableSet / unmodifiableMap?
basics
~20 sList.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.
What are the Collections.emptyList and singletonList factories, and why are they useful?
basics
~20 sCollections.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.
What are the time complexities of common operations on ArrayList versus LinkedList, and when would you pick one over the other?
basics
~20 sArrayList 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.
What questions do you ask yourself to decide between a List, a Set, and a Map for a given task?
basics
~20 sUse 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.
What is the average and worst-case time complexity of HashMap get and put, and what makes the average case constant?
basics
~20 sHashMap 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.
When would you choose ArrayList over LinkedList, and when (if ever) the reverse?
basics
~20 sUse 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.
How do you choose among HashMap, LinkedHashMap, and TreeMap (and the equivalent Set variants)?
basics
~20 sHashMap 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.