Java Collection Framework Interview Questions - Part 2
This guide covers advanced comparisons, internal workings of Maps, and best practices for using the Collection Framework.
1. ArrayList vs. LinkedList: When to use what?
The choice depends on the operations you perform most frequently:
- ArrayList: Uses a Dynamic Array. It supports Random Access with O(1) complexity, making it ideal for search/retrieval operations.
- LinkedList: Uses a Doubly Linked List. While searching is slow (O(n)), insertions and deletions in the middle of the list are very fast (O(1)) because no bit-shifting is required.
2. HashMap vs. TreeMap vs. LinkedHashMap
| Feature | HashMap | TreeMap | LinkedHashMap |
|---|---|---|---|
| Ordering | Random / Unordered | Natural Ordering (Sorted) | Insertion Order |
| Search/Insert | O(1) | O(log n) | O(1) |
| Null Keys | One null key allowed | No null keys | One null key allowed |
| Structure | Hash Table | Red-Black Tree | Hash Table + Doubly Linked List |
3. What is a PriorityQueue?
A PriorityQueue is a special type of queue where elements are processed based on their priority rather than their insertion order (FIFO).
- A higher-priority element is served before a lower-priority element.
- Default priority is determined by natural ordering or a custom
Comparator.
4. Requirements for a Map Key
Not every class can be a key. To use a custom object as a key:
- Override
hashCode()andequals(): You must follow the contract to ensure objects are stored and retrieved from the correct bucket. - Immutability: The key should ideally be immutable (like
StringorInteger). If the key's state changes, its hashcode will change, and you will lose the ability to find the object in the map.