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 pageshowhide
explore
- Collection Hierarchy & Interfaces5 questions
- Iterable & Collection Interfaces5 questions
- List Implementations19 questions
- ArrayList5 questions
- LinkedList4 questions
- ArrayList vs LinkedList5 questions
- subList Views & indexOf5 questions
- Set Implementations15 questions
- HashSet & LinkedHashSet5 questions
- TreeSet & NavigableSet5 questions
- Set Uniqueness & CopyOnWriteArraySet5 questions
- Map Implementations27 questions
- HashMap5 questions
- LinkedHashMap & LRU5 questions
- TreeMap & NavigableMap6 questions
- Map.Entry & Default/Compute Methods6 questions
- Queue & Deque10 questions
- Queue, Deque & ArrayDeque5 questions
- PriorityQueue5 questions
- Iterators & Traversal15 questions
- Iterator & ListIterator5 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
121 · 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 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.
What are the Collection bulk operations (addAll, removeAll, retainAll, containsAll, clear), and what set-like semantics do they implement?
basics
~20 sThey 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.
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; the modern idiom 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 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.
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. Changes to the view show up in the original list and vice versa. The range is from inclusive to to exclusive.
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 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.
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.
Explain the equals/hashCode contract and why violating it breaks a HashSet.
basics
~10 sIf 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.
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 is the cheapest way to read both key and value together.
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 — 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.
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 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.
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.
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?
basics
~10 sQueue 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.
Why is iterating over a PriorityQueue not the same as getting elements in sorted order?
basics
~10 sIterating (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.
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 sIt'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.
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 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 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.
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 sIt'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).
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 sThey 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.
How do Collections.sort and Collections.binarySearch work, and what are their requirements and complexity?
basics
~10 sCollections.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.
How do List.of / Set.of / Map.of differ from Collections.unmodifiableList / unmodifiableSet / unmodifiableMap?
basics
~20 sThe 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.
What are the Collections.emptyList and singletonList factories, and why are they useful?
basics
~10 sCollections.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.
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 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.
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 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.
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.