Java Collection Framework Interview Question
On this page20
- 1What is the Java Collection Framework?
- 2What are the main interfaces in the Java Collection Framework?
- 3What is the difference between ArrayList and LinkedList?
- 4What is the difference between HashSet and TreeSet?
- 5How does HashMap work internally?
- 6What is the difference between HashMap and Hashtable?
- 7What is the difference between ArrayList and Vector?
- 8What is the difference between Comparable and Comparator?
- 9What is the difference between fail-fast and fail-safe iterators?
- 10What is the difference between HashMap and TreeMap?
- 11What is the difference between Iterator and ListIterator?
- 12What is the difference between Queue and Deque?
- 13What is the difference between Set and List?
- 14What is the difference between ConcurrentHashMap and SynchronizedMap?
- 15What is the difference between peek(), poll(), and remove() in a Queue?
- 16How does LinkedHashMap maintain insertion order?
- 17What is the difference between HashSet and LinkedHashSet?
- 18What is the purpose of PriorityQueue?
- 19How do you sort a collection in Java?
- 20What is the difference between CopyOnWriteArrayList and ArrayList?
1. What is the Java Collection Framework?
The Java Collection Framework is a set of classes and interfaces that provide data structures (like lists, sets, maps) and algorithms (like sorting, searching). It is part of the java.util package and helps manage and manipulate collections of objects efficiently.
2. What are the main interfaces in the Java Collection Framework?
- Collection: The root interface for all collections.
- List: Ordered collection (e.g., ArrayList, LinkedList).
- Set: Unordered collection with no duplicate elements (e.g., HashSet, TreeSet).
- Queue: Collection for holding elements prior to processing (e.g., PriorityQueue).
- Map: Key-value pairs (e.g., HashMap, TreeMap).
3. What is the difference between ArrayList and LinkedList?
Feature | ArrayList | LinkedList |
|---|---|---|
Implementation | Uses a dynamic array. | Uses a doubly linked list. |
Access Time | O(1) for random access. | O(n) for random access. |
Insertion/Deletion | Slow for large data (O(n)). | Faster for large data (O(1) at head/tail). |
Memory | Less memory overhead. | More memory overhead (node pointers). |
4. What is the difference between HashSet and TreeSet?
Feature | HashSet | TreeSet |
|---|---|---|
Order | Unordered. | Sorted in natural or custom order. |
Performance | O(1) for add, remove, search. | O(log n) for add, remove, search. |
Null Values | Allows one null value. | Does not allow null values. |
5. How does HashMap work internally?
- Hashing: Keys are hashed using their hashCode() to determine the bucket.
- Collision Handling: If two keys hash to the same bucket:
- Key Lookup: HashMap first finds the bucket using the hash, then compares keys using equals().
- Java 7: Uses a linked list.
- Java 8+: Uses a red-black tree for better performance when collisions are high.
6. What is the difference between HashMap and Hashtable?
Feature | HashMap | Hashtable |
|---|---|---|
Thread Safety | Not synchronized. | Synchronized (thread-safe). |
Null Keys/Values | Allows one null key and multiple null values. | Does not allow null keys or values. |
Performance | Faster (no synchronization). | Slower (synchronization overhead). |
7. What is the difference between ArrayList and Vector?
Feature | ArrayList | Vector |
|---|---|---|
Thread Safety | Not synchronized. | Synchronized (thread-safe). |
Performance | Faster (no synchronization). | Slower (synchronization overhead). |
Growth | Increases by 50% when full. | Doubles its size when full. |
8. What is the difference between Comparable and Comparator?
- Comparable: Used to define natural ordering of objects. Implemented using the compareTo() method.
- Comparator: Used to define custom ordering. Implemented using the compare() method.
Example:
class Employee implements Comparable<Employee> {
private int id;
public int compareTo(Employeee) {
return this.id-e.id; // Natural ordering by ID
}
}
9. What is the difference between fail-fast and fail-safe iterators?
- Fail-Fast: Throws ConcurrentModificationException if the collection is modified during iteration (e.g., ArrayList, HashMap).
- Fail-Safe: Does not throw an exception as it works on a copy of the collection (e.g., CopyOnWriteArrayList, ConcurrentHashMap).
10. What is the difference between HashMap and TreeMap?
Feature | HashMap | TreeMap |
|---|---|---|
Order | Unordered. | Sorted by natural or custom order. |
Performance | O(1) for add, remove, search. | O(log n) for add, remove, search. |
Null Keys | Allows one null key. | Does not allow null keys. |
11. What is the difference between Iterator and ListIterator?
Feature | Iterator | ListIterator |
|---|---|---|
Traversal | Forward only. | Forward and backward. |
Applicable | All collections. | Only for List implementations. |
Add Elements | Not supported. | Supported. |
12. What is the difference between Queue and Deque?
- Queue: A collection that follows FIFO (First-In-First-Out) order (e.g., PriorityQueue).
- Deque: A double-ended queue that allows insertion and removal from both ends (e.g., ArrayDeque).
13. What is the difference between Set and List?
Feature | Set | List |
|---|---|---|
Duplicates | Does not allow duplicates. | Allows duplicates. |
Order | Unordered (except LinkedHashSet). | Ordered. |
14. What is the difference between ConcurrentHashMap and SynchronizedMap?
- ConcurrentHashMap: Allows concurrent access by dividing the map into segments. Better performance in multithreaded environments.
- SynchronizedMap: Synchronizes the entire map, leading to slower performance.
15. What is the difference between peek(), poll(), and remove() in a Queue?
- peek(): Retrieves the head of the queue without removing it. Returns null if the queue is empty.
- poll(): Retrieves and removes the head of the queue. Returns null if the queue is empty.
- remove(): Retrieves and removes the head of the queue. Throws NoSuchElementException if the queue is empty.
16. How does LinkedHashMap maintain insertion order?
LinkedHashMap uses a doubly linked list to maintain the order of elements as they are inserted. It also allows access-order iteration if configured.
17. What is the difference between HashSet and LinkedHashSet?
Feature | HashSet | LinkedHashSet |
|---|---|---|
Order | Unordered | Maintains insertion order. |
Performance | Slightly faster. | Slightly slower due to ordering. |
18. What is the purpose of PriorityQueue?
PriorityQueue is a queue where elements are ordered based on their natural ordering or a custom comparator. The head of the queue is the smallest or highest-priority element.
19. How do you sort a collection in Java?
- Use Collections.sort() for lists.
- Use TreeSet or TreeMap for sorted sets or maps.
- Use Comparator for custom sorting.
Example:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names); // Natural order
Collections.sort(names, Comparator.reverseOrder()); // Custom order
20. What is the difference between CopyOnWriteArrayList and ArrayList?
- CopyOnWriteArrayList: Thread-safe; creates a new copy of the list on every modification. Suitable for read-heavy operations.
- ArrayList: Not thread-safe; faster for single-threaded operations.
