Top Java Collections Interview Questions with Answers
The Java Collections Framework is a favorite interview topic since it tests both API knowledge and understanding of underlying data structures. Here are commonly asked questions.
1. What is the difference between Collection and Collections?
Collection is an interface that represents a group of objects, while Collections is a utility class with static methods for operating on collections, like sorting and searching.
2. How does HashMap handle collisions?
When two keys hash to the same bucket, HashMap stores them as a linked list (or a tree, for large buckets since Java 8) within that bucket and uses equals() to distinguish entries.
3. What is the difference between HashMap and Hashtable?
HashMap is not synchronized and allows one null key, while Hashtable is synchronized (thread-safe) and doesn't allow null keys or values.
4. What is the difference between Comparable and Comparator?
Comparable defines natural ordering inside the class itself via compareTo(), while Comparator defines custom ordering externally via compare().
List<String> names = new ArrayList<>(List.of("Riya", "Aman"));
names.sort(Comparator.reverseOrder());
5. How do you make a collection thread-safe?
You can wrap it using Collections.synchronizedList(), or use classes from java.util.concurrent like ConcurrentHashMap and CopyOnWriteArrayList.
6. What is the difference between Iterator and ListIterator?
Iterator can traverse a collection forward and supports removal; ListIterator extends Iterator and supports traversing both forward and backward, plus adding and setting elements.
7. What is fail-fast vs fail-safe iteration?
Fail-fast iterators (like ArrayList's) throw a ConcurrentModificationException if the collection is modified during iteration; fail-safe iterators (like ConcurrentHashMap's) work on a separate copy or snapshot and don't throw this exception.
8. How does TreeMap maintain sorted order?
TreeMap is backed by a red-black tree, which keeps keys sorted according to their natural ordering or a provided Comparator.
9. What is the difference between poll() and remove() in Queue?
poll() returns null if the queue is empty, while remove() throws an exception in the same situation.
10. When would you use an ArrayDeque instead of a Stack?
ArrayDeque is generally preferred over the legacy Stack class because it's faster and not burdened by unnecessary synchronization.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.