[Go to site: main page, start]

0% found this document useful (0 votes)
2 views6 pages

Java Collection Interview

Uploaded by

jonas48490
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Java Collection Interview

Uploaded by

jonas48490
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Here’s a structured, concise answer to your **Java Collections

Framework** questions, written in the style you’d use in an


interview (theory + examples, minimal code).

---

## 1. General Collections Framework

**What is the Collections Framework?**


It’s a unified architecture in Java for storing, retrieving, and
manipulating groups of objects. It includes interfaces (`List`, `Set`,
`Queue`, `Map`), implementations (`ArrayList`, `HashMap`), and
algorithms (`sort`, `binarySearch`).

**Collection hierarchy diagram (simplified):**


```
Iterable (root)

└── Collection
├── List
│ ├── ArrayList
│ ├── LinkedList
│ └── Vector → Stack
├── Set
│ ├── HashSet → LinkedHashSet
│ └── TreeSet
└── Queue
├── PriorityQueue
└── Deque → ArrayDeque

Map (separate hierarchy)


├── HashMap → LinkedHashMap
├── TreeMap
├── Hashtable
└── ConcurrentHashMap
```

**Difference between `Collection` and `Collections`?**


- `Collection` → root interface (e.g., `List`, `Set`).
- `Collections` → utility class with static methods (e.g.,
`[Link]()`, `[Link]()`).

**Root interface of Java Collections Framework?**


`Iterable` (for `Collection`). But for `Collection` hierarchy, it’s
`Collection`. `Map` is separate.

**Why is `Map` not part of `Collection` interface?**


Because `Map` stores key-value pairs, not a single collection of
elements. Its operations (e.g., `get(key)`) don’t fit the
`add(element)`, `remove(element)` pattern of `Collection`.

---

## 2. List Interface

**ArrayList vs LinkedList?**

| Aspect | ArrayList | LinkedList |


|--------|-----------|-------------|
| Internal | Dynamic array | Doubly linked list |
| Get(index) | O(1) – fast | O(n) – slow |
| Add/delete at end | Amortized O(1) | O(1) |
| Add/delete in middle | O(n) – shifts | O(n) – but only pointer
changes, no shift |
| Memory | Less overhead | More (stores prev/next pointers) |

**When to use ArrayList vs LinkedList?**


- **ArrayList:** Frequent random access (`get`), iterating, mostly
adding at end.
- **LinkedList:** Frequent insertions/deletions in the middle (e.g.,
queue, deque operations).

**ArrayList vs Vector?**
- `Vector` is **synchronized** (thread-safe); `ArrayList` is not.
- `Vector` doubles its size; `ArrayList` grows by 50%.
- `Vector` is legacy; use `ArrayList` +
`[Link]()` if needed.

**What is `CopyOnWriteArrayList`?**
A thread-safe variant where every mutation creates a new copy of
the array. Used when reads vastly outnumber writes (e.g., listener
lists).

**How does `ArrayList` work internally?**


It maintains an `Object[]` array. When capacity is reached, it
creates a new array of size `oldCapacity + (oldCapacity >> 1)`
(50% growth) and copies elements.

---

## 3. Set Interface

**HashSet vs LinkedHashSet vs TreeSet?**

| Feature | HashSet | LinkedHashSet | TreeSet |


|---------|---------|---------------|---------|
| Order | No order | Insertion order | Sorted (natural / comparator) |
| Null | One null allowed | One null allowed | No null (throws NPE if
comparator doesn’t handle it) |
| Performance | O(1) avg | O(1) avg | O(log n) |
| Internal | HashMap | LinkedHashMap | TreeMap (Red-Black tree)
|

**Why is `HashSet` faster than `TreeSet`?**


`HashSet` uses hash-based lookup (O(1) average), while `TreeSet`
maintains sorted order with tree structure (O(log n)).

**Can we store null in `HashSet`? TreeSet?**


- `HashSet`: yes (one null).
- `TreeSet`: no – because null cannot be compared to other
elements for ordering.

**What is `LinkedHashSet`?**
HashSet + a doubly linked list preserving insertion order. Use
when you need uniqueness + predictable iteration order.

---

## 4. Queue & Deque

**Queue vs Deque?**
- `Queue` – single-ended (FIFO: offer/poll/peek).
- `Deque` – double-ended (insert/remove from both ends:
addFirst/removeLast, etc.).

**What is `PriorityQueue`?**
Implements a **min-heap** (by default). Elements are ordered by
natural order or a `Comparator`. `poll()` always returns the
smallest element. Not thread-safe.

**Explain `ArrayDeque` and its advantages.**


Resizable array implementation of `Deque`. Faster than
`LinkedList` for stack/queue usage (no node overhead, better
cache locality). Use as a replacement for `Stack` and `LinkedList`
when only deque operations are needed.

**What is `BlockingQueue`?**
A queue that blocks when empty (take) or full (put).
Implementations:
- `ArrayBlockingQueue` (bounded, FIFO)
- `LinkedBlockingQueue` (optionally bounded)
- `PriorityBlockingQueue` (unbounded, heap-ordered)

---
## 5. Map Interface (High Weightage)

**HashMap vs LinkedHashMap vs TreeMap?**

| Feature | HashMap | LinkedHashMap | TreeMap |


|---------|---------|---------------|---------|
| Order | None | Insertion order | Sorted by key |
| Null keys | One allowed | One allowed | No (throws NPE) |
| Performance | O(1) | O(1) | O(log n) |
| Internal | Array of nodes | + double linked list | Red-Black tree |

**How does `HashMap` work internally?**


- Array of `Node<K,V>` (called table).
- `put(key, value)` → `hashCode()` → index = (n-1) & hash →
insert/update.
- If two keys have same index → **collision** → stored as
`LinkedList` (or `TreeNode` after threshold).
- `get(key)` → hash to find bucket, then traverse list/tree.

**Changes in Java 8+ for `HashMap`?**


When a bucket has **more than 8** entries and total size > 64, the
linked list converts to a **balanced tree** (TreeNode) for O(log n)
search. If size drops below 6, it converts back.

**HashMap vs Hashtable?**
- `Hashtable` is synchronized (slow), `HashMap` is not.
- `Hashtable` does **not** allow null key/value; `HashMap` allows
one null key, multiple null values.
- `Hashtable` is legacy.

**What is `ConcurrentHashMap`?**
Thread-safe `HashMap` using **bucket locking** (fine-grained
concurrency). Better than `Hashtable` because it allows concurrent
reads and limited concurrent writes.

**Can we store null key or value in `HashMap`?**


Yes – one null key, many null values. But `ConcurrentHashMap`
does **not** allow null (to avoid ambiguity in concurrent
operations).

**Fail-fast vs fail-safe iterator?**


- **Fail-fast**: Throws `ConcurrentModificationException` if map is
modified after iterator creation (e.g., `HashMap`, `ArrayList`).
- **Fail-safe**: Works on a snapshot; modifications are allowed
(e.g., `ConcurrentHashMap`, `CopyOnWriteArrayList`).

**How does `HashMap` handle collisions?**


1. Separate chaining: store multiple nodes in same bucket.
2. Java 8+: if chain length > 8 → convert to `TreeNode` (Red-Black
tree).
3. If key is `Comparable`, tree ordering uses `compareTo()` to
speed up searches.

---

## 6. Internal Working & Performance

**Time complexity:**
- `[Link]/put/remove` → O(1) average, O(log n) worst (tree
bucket).
- `[Link]()` → O(n)
- `[Link]()` → O(1) average

**Load factor & initial capacity in `HashMap`?**


- `load factor` (default 0.75) – how full map can be before resize.
- `initial capacity` (default 16) – number of buckets.
Resize occurs when `size > capacity * load factor`.

**Rehashing:**
When resizing, each existing node’s hash is recomputed into a new
bucket index (due to changed array length). Costly – O(n).

**Comparable vs Comparator?**

| Comparable | Comparator |
|------------|------------|
| `compareTo(obj)` | `compare(o1, o2)` |
| Natural ordering | Custom/alternative ordering |
| Implemented by the class | External class / lambda |
| `[Link](list)` | `[Link](list, comparator)` |

Example: `String` is `Comparable` (lexicographic). You can give a


`Comparator` to sort by length.

---

## 7. Java 8+ Enhancements

**`forEach()`, `stream()` in Collections**


- `[Link]([Link]::println)` – internal iteration.
- `[Link]().filter(...).collect(...)` – functional style, lazy
evaluation.

**Convert `List` to `Map` using Streams**


```java
Map<Integer, String> map = [Link]()
.collect([Link](Item::getId, Item::getName));
```

**`Collectors` class useful methods:**


`toList()`, `toSet()`, `toMap()`, `groupingBy()`, `partitioningBy()`,
`joining()`.

---

## 8. Tricky & Advanced Questions

**`SynchronizedList` / `SynchronizedMap` – how to create?**


`[Link](new ArrayList<>())`. Every method
is synchronized on the wrapper object. Less performant than
`ConcurrentHashMap`.

**Immutable Collection – how to create in Java 9+?**


`[Link]()`, `[Link]()`, `[Link]()`. Any modification throws
`UnsupportedOperationException`.

**Iterator vs ListIterator?**
- `Iterator` – forward only, remove allowed.
- `ListIterator` – bidirectional, also supports `set()` and `add()`.

**Why is `String` preferred as a key in `HashMap`?**


- Immutable → hash code is cached and never changes.
- `equals()` and `hashCode()` are correctly and efficiently
implemented.
- Prevents key corruption after insertion.

**What happens if you put a mutable object as a key in `HashMap`


then modify it?**
The hash code changes, but the key is still stored in the old bucket.
`get()` will fail (looks in wrong bucket). Causes memory leak.

**Explain `WeakHashMap`.**
Uses `WeakReference` for keys. If a key is only referenced inside
the map, GC can reclaim it. Entry is auto-removed. Used for
caches.

**What is `IdentityHashMap`?**
Uses reference equality (`==`) instead of `equals()` for key
comparison. Also uses `[Link]()`. Used in
serialization, object graph copies.

You might also like