Java Collection & Collections Framework
Interview Questions & Answers — Detailed Revision Guide
Target: Java Developer interview • Focus: Core Java, Collection Framework, Java 8+ streams, concurrency and practical
coding.
1. COLLECTION BASICS
1. What is a Collection in Java?
Answer: A Collection is an object that groups multiple elements into a single unit. The Java Collections Framework
provides interfaces, implementations and algorithms for storing and manipulating groups of objects. Examples include
List, Set and Queue.
2. What is the difference between Collection and Collections?
Answer: Collection is an interface in [Link] and is the root interface for List, Set and Queue. Collections is a utility
class in [Link] containing static methods such as sort(), reverse(), shuffle(), min(), max(), binarySearch(),
synchronizedCollection() and unmodifiableCollection().
3. What is the difference between Collection and Collections Framework?
Answer: Collection is one interface. The Collections Framework is the complete architecture containing interfaces such
as List, Set, Queue and Map, concrete implementations such as ArrayList, HashSet, LinkedList, TreeSet and HashMap,
plus algorithms and utility support.
4. Is Map a child of Collection?
Answer: No. Map does not extend Collection because it stores key-value mappings rather than individual elements.
HashMap, LinkedHashMap, TreeMap and Hashtable are Map implementations.
5. What are the main Collection interfaces?
Answer: List: ordered, duplicates allowed. Set: duplicates not allowed. Queue: designed mainly for processing elements
in a particular order. Deque: double-ended queue. Map is separate from Collection and stores key-value pairs.
2. LIST — ARRAYLIST, LINKEDLIST, VECTOR
6. ArrayList vs LinkedList?
Answer: ArrayList uses a dynamically growing array, so random access by index is fast, typically O(1). Inserting/removing
in the middle generally costs O(n) because elements may need shifting. LinkedList is a doubly linked list; access by index
is O(n), while insertion/removal is efficient once the node/position is known. In real applications, ArrayList is usually the
default choice.
7. ArrayList vs Vector?
Answer: Both are dynamic arrays. Vector's legacy methods are synchronized, which adds synchronization overhead.
ArrayList is generally preferred in modern code unless legacy compatibility or specific synchronization behavior is
required.
8. How does ArrayList grow?
Answer: When capacity is insufficient, ArrayList creates a larger backing array and copies existing elements into it. The
exact growth policy is implementation-dependent, so interviewers may expect the concept rather than relying on a specific
percentage.
9. Can ArrayList contain null?
Answer: Yes. ArrayList can contain multiple null elements.
10. Can LinkedList be used as Stack and Queue?
Answer: Yes. LinkedList implements both List and Deque, so it can support queue/deque/stack-like operations. For
stack/queue semantics, ArrayDeque is often preferred for non-concurrent use.
11. When should you use ArrayList vs LinkedList?
Answer: Use ArrayList for frequent reads/index access and general-purpose lists. Use LinkedList only when its
linked-node behavior is actually beneficial, especially operations at the ends; do not assume LinkedList is faster for every
insertion/removal.
3. SET — HASHSET, LINKEDHASHSET, TREESET
12. What is a Set?
Answer: A Set stores unique elements. Duplicate elements are not retained according to the Set contract.
13. How does HashSet prevent duplicates?
Answer: HashSet is backed by a HashMap in typical JDK implementations. When add() is called, hashing determines a
bucket and equality checks determine whether an equivalent key already exists. hashCode() and equals() therefore
matter.
14. HashSet vs LinkedHashSet vs TreeSet?
Answer: HashSet provides no guaranteed iteration order. LinkedHashSet maintains insertion order. TreeSet maintains
sorted order according to natural ordering or a Comparator. Typical basic operation complexity is near O(1) for
HashSet/LinkedHashSet and O(log n) for TreeSet.
15. Can TreeSet contain null?
Answer: Do not rely on null in TreeSet. With natural ordering, comparing null with non-null elements causes
NullPointerException. Comparator behavior can change this, but null handling should be explicit.
16. Why must equals() and hashCode() be consistent?
Answer: If two objects are equal according to equals(), they must return the same hashCode(). Hash-based collections
use hashCode() to locate a bucket and equals() to verify equality. Violating the contract can cause failed lookups or
duplicate-like behavior.
17. What happens if a field used in hashCode changes after adding an object to
HashSet?
Answer: The object can become effectively unreachable because its new hash may point to a different bucket. This is
why keys/elements used in hash-based collections should generally be immutable with respect to equality/hash fields.
4. MAP — HASHMAP AND RELATED TYPES
18. What is HashMap?
Answer: HashMap stores key-value pairs. It permits one null key and multiple null values, does not guarantee iteration
order, and provides expected constant-time get/put performance under good hash distribution.
19. How does HashMap work internally?
Answer: Conceptually, HashMap uses an array of buckets. A key's hash is processed to choose a bucket. If multiple keys
land in the same bucket, entries are linked and, in modern Java implementations, heavily-collided buckets can be treeified
under suitable conditions. Equality is then used to identify the exact key.
20. Why are both hashCode() and equals() used in HashMap?
Answer: hashCode() narrows the search to a bucket; equals() identifies the exact key among entries in that bucket. Equal
keys must have equal hash codes.
21. HashMap vs Hashtable?
Answer: HashMap is modern, unsynchronized and permits null key/value entries. Hashtable is a legacy synchronized
Map and does not permit null keys or values. For concurrent applications, prefer modern concurrent collections such as
ConcurrentHashMap when appropriate.
22. HashMap vs LinkedHashMap?
Answer: LinkedHashMap maintains a predictable iteration order, normally insertion order; it can also be configured for
access order, which is useful for LRU-style caches. HashMap does not guarantee iteration order.
23. HashMap vs TreeMap?
Answer: HashMap provides expected O(1) basic lookup and no sorted-order guarantee. TreeMap keeps keys sorted and
basic operations are O(log n). TreeMap uses natural ordering or a Comparator.
24. Can HashMap have duplicate keys?
Answer: No. A key can appear only once. Putting a value with an existing key replaces the old value.
25. What is the difference between put() and putIfAbsent()?
Answer: put() associates the supplied value with the key, replacing an existing mapping. putIfAbsent() inserts only when
the key is not already mapped to a value (subject to Map's null-related semantics).
5. QUEUE, DEQUE AND PRIORITYQUEUE
26. What is Queue?
Answer: Queue is designed for holding elements before processing. Common methods include offer(), poll() and peek().
offer/poll are useful because they return a status/null rather than necessarily throwing for capacity/empty conditions.
27. poll() vs remove()?
Answer: poll() retrieves and removes the head, returning null if empty. remove() retrieves and removes the head but
throws NoSuchElementException if the queue is empty.
28. peek() vs element()?
Answer: peek() returns the head without removing it and returns null when empty. element() returns the head without
removing it but throws NoSuchElementException when empty.
29. What is PriorityQueue?
Answer: PriorityQueue orders elements according to natural ordering or a supplied Comparator. The head is the
highest-priority element according to that ordering. Iterating the queue does not mean the entire iteration is sorted.
30. What is Deque?
Answer: Deque means double-ended queue. It supports insertion and removal at both ends. ArrayDeque is a common
implementation for stack/queue behavior in single-threaded code.
6. ITERATION AND FAIL-FAST
31. Iterator vs ListIterator?
Answer: Iterator supports forward traversal and removal through [Link](). ListIterator is for Lists and supports
bidirectional traversal plus add(), set() and index-related operations.
32. What is ConcurrentModificationException?
Answer: It can occur when a collection is structurally modified while it is being iterated in a way that violates the iterator's
expected modification rules. It is commonly seen with fail-fast iterators; it should not be treated as a thread-safety
guarantee.
33. How can you safely remove while iterating?
Answer: Use [Link]() when supported, or use collection methods such as removeIf() where appropriate. Avoid
directly modifying a collection structurally inside an enhanced for-loop.
Example:
Iterator<String> it = [Link]();
while ([Link]()) {
String s = [Link]();
if ([Link]("A")) [Link]();
}
7. COMPARABLE AND COMPARATOR
34. Comparable vs Comparator?
Answer: Comparable defines an object's natural ordering through compareTo() inside the class. Comparator defines an
external/custom ordering through compare(). Comparator lets you create multiple sorting strategies without changing the
class.
35. What should compareTo/compare return?
Answer: A negative value means the first value should come before the second, zero means they compare as equal for
ordering, and a positive value means it should come after. Do not rely on the exact numeric value.
36. Can a Comparator be used with TreeSet?
Answer: Yes. TreeSet can receive a Comparator in its constructor. Important: if compare() returns zero for two objects,
TreeSet treats them as the same for set membership even if equals() says otherwise.
8. IMMUTABLE COLLECTIONS AND UTILITY METHODS
37. [Link]() vs [Link]()?
Answer: [Link]() returns a fixed-size list backed by the array; set() is supported but add/remove are not. [Link]()
creates an unmodifiable list, rejects null elements, and is intended for immutable-style collection creation.
38. [Link]() vs [Link]()?
Answer: unmodifiableList() gives an unmodifiable view over the supplied list, so changes to the original list can be visible.
[Link]() creates an unmodifiable copy and rejects null elements.
39. [Link]() vs CopyOnWriteArrayList?
Answer: synchronizedList() wraps a list with synchronization for individual operations. CopyOnWriteArrayList creates a
new underlying array for writes, making iteration friendly for read-heavy, low-write workloads. It is not a universal
replacement for synchronization.
9. CONCURRENT COLLECTIONS
40. HashMap vs ConcurrentHashMap?
Answer: HashMap is not thread-safe. ConcurrentHashMap is designed for concurrent access and provides thread-safe
operations without locking the entire map for ordinary access. ConcurrentHashMap does not permit null keys or null
values.
41. What is CopyOnWriteArrayList?
Answer: It is a thread-safe List optimized for scenarios with many reads/iterations and relatively few writes. Each write
copies the underlying array, so frequent writes can be expensive.
42. What is BlockingQueue?
Answer: A BlockingQueue supports producer-consumer patterns. Operations can wait when the queue is empty or full
depending on the method and capacity. Common implementations include ArrayBlockingQueue and
LinkedBlockingQueue.
43. Why use ConcurrentHashMap instead of [Link]()?
Answer: ConcurrentHashMap is designed for higher concurrency and offers useful atomic compound operations such as
putIfAbsent(), computeIfAbsent() and merge(). synchronizedMap serializes access through synchronization around the
map.
10. JAVA 8+ COLLECTION INTERVIEW QUESTIONS
44. How do you iterate a Map using Java 8?
Answer: Use entrySet() with forEach, for example: [Link]((k, v) -> [Link](k + "=" + v)). For processing,
entrySet() is generally preferable when both key and value are needed.
45. How do you remove elements using Java 8?
Answer: Use removeIf() where suitable: [Link](x -> x < 10). This expresses the condition clearly and avoids unsafe
structural modification during enhanced iteration.
46. How do streams work with collections?
Answer: A collection provides data; stream() creates a pipeline for declarative processing. Intermediate operations such
as filter/map/sorted are lazy; terminal operations such as collect/count/forEach trigger processing.
47. Difference between map() and flatMap()?
Answer: map transforms each element into one result. flatMap transforms each element into a stream and flattens the
resulting streams into one stream, useful for nested collections.
48. [Link]() vs [Link]()?
Answer: toList() collects stream elements into a List; duplicates can remain. toSet() collects into a Set, so duplicates
according to the Set semantics are removed. Do not assume a specific concrete implementation unless documented.
11. COMPLEXITY — MUST REMEMBER
Structure Access/Search Insert/Delete Ordering
ArrayList index O(1); search O(n) end amortized O(1); middle O(n) insertion order
LinkedList index O(n) ends O(1); arbitrary position needs traversal
insertion order
HashSet expected O(1) expected O(1) no guaranteed order
TreeSet O(log n) O(log n) sorted
HashMap expected O(1) expected O(1) no guaranteed order
TreeMap O(log n) O(log n) sorted by key
12. TOP TRICK QUESTIONS
49. Why is String a good HashMap key?
Answer: String is immutable, has stable equals/hashCode behavior, and is widely used as a value object. Because its
state does not change after creation, its hash-based lookup behavior remains stable.
50. What happens if two different keys have the same hashCode?
Answer: They collide into the same bucket. HashMap resolves the collision by comparing keys using equals(), so
different keys can coexist if equals() returns false.
51. Does HashMap maintain insertion order?
Answer: No. HashMap provides no guaranteed iteration order. If insertion order matters, use LinkedHashMap.
52. Does PriorityQueue iteration return sorted elements?
Answer: No. Only the head is guaranteed to be the next element according to the queue ordering. To retrieve elements in
priority order, repeatedly poll().
53. Why is ArrayDeque usually preferred over Stack?
Answer: Stack is a legacy class extending Vector. ArrayDeque provides modern Deque operations and is typically
preferred for stack behavior in non-concurrent code.
54. Can you modify a key after putting it in HashMap?
Answer: Technically the object may be mutable, but changing fields involved in equals/hashCode after insertion can
make the mapping difficult or impossible to find. Prefer immutable keys.
55. What is load factor in HashMap?
Answer: Load factor is a threshold-related parameter controlling when the table is resized as it becomes populated. The
commonly used default is 0.75, balancing space and lookup performance.
56. What is the difference between size and capacity in ArrayList?
Answer: Size is the number of actual elements stored. Capacity is the current size of the internal storage available before
another growth operation is needed.
13. PRACTICAL CODING QUESTIONS
57. Remove duplicates while preserving insertion order
Use LinkedHashSet when you want uniqueness plus insertion order.
List<Integer> result = new ArrayList<>(new LinkedHashSet<>(list));
58. Count frequency of each element
Map<String, Integer> freq = new HashMap<>();
for (String s : list) {
[Link](s, [Link](s, 0) + 1);
}
59. Sort a list of employees by salary
[Link]([Link](Employee::getSalary));
60. Find duplicate elements using a Set
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (Integer x : list) {
if () [Link](x);
}
14. RAPID-FIRE QUESTIONS FOR YOUR INTERVIEW
• ArrayList or LinkedList for most use cases? → ArrayList.
• Unique elements? → Set.
• Sorted unique elements? → TreeSet.
• Insertion-order unique elements? → LinkedHashSet.
• Key-value data? → Map.
• Sorted keys? → TreeMap.
• Insertion/access order map? → LinkedHashMap.
• Thread-safe concurrent map? → ConcurrentHashMap.
• Double-ended queue? → Deque / ArrayDeque.
• Producer-consumer? → BlockingQueue.
• Natural ordering? → Comparable.
• Custom ordering? → Comparator.
• Remove during iteration? → [Link]() / removeIf().
• Map duplicate key? → No; existing value is replaced.
• HashMap nulls? → One null key and multiple null values.
• ConcurrentHashMap nulls? → No null keys or values.
15. INTERVIEW ANSWER TEMPLATE
When the interviewer asks: “Explain HashMap.”
Answer in this order: definition → internal working → hashCode/equals → collision → complexity → null behavior →
thread safety → practical use case. Example: “HashMap stores key-value pairs and provides expected O(1) lookup. It
uses hashing to locate a bucket and equals() to identify the key. It allows one null key and multiple null values, does not
guarantee order, and is not thread-safe. For concurrent access I would consider ConcurrentHashMap.”
16. LAST-MINUTE REVISION CHECKLIST
• Collection vs Collections vs Collections Framework
• List / Set / Queue / Deque / Map
• ArrayList vs LinkedList
• HashSet / LinkedHashSet / TreeSet
• HashMap internal working and collisions
• HashMap vs LinkedHashMap vs TreeMap
• equals() and hashCode() contract
• Comparable vs Comparator
• Iterator vs ListIterator
• Fail-fast and ConcurrentModificationException
• ConcurrentHashMap and CopyOnWriteArrayList
• Queue: offer/poll/peek
• PriorityQueue
• [Link](), [Link](), [Link]()
• Streams and Collectors
• Time complexities
• At least 3 coding problems: frequency, duplicates, sorting
Good luck for Wednesday — focus especially on HashMap internal working, ArrayList vs LinkedList, HashSet,
equals/hashCode, Comparable vs Comparator, and ConcurrentHashMap.