Skip to content
C

Java Interview Questions

Collections Interview Questions

List/Set/Queue/Map implementations, Comparable vs Comparator, HashMap internals, and fail-fast iteration.

Question 1: What is the Java Collection Framework?

Ans

The Collection Framework is a unified set of interfaces and classes in java.util for storing, organizing, and manipulating groups of objects, such as List, Set, Queue, and Map along with their common implementations. It replaces older, inconsistent structures with a common architecture, so algorithms and utility methods work across different collection types.

Example

java
List<String> names = new ArrayList<>(); names.add("Amit"); names.add("Neha");

Important Point

Map is part of the Collections Framework conceptually but does not extend the Collection interface, since it stores key-value pairs rather than single elements.

Question 2: When would you use a List, a Set, a Queue, or a Map?

Ans

Use a List when order matters and duplicates are allowed; use a Set when you need uniqueness and don't care about, or want a specific, ordering; use a Queue when you need FIFO or priority-based processing order, such as task scheduling; use a Map when you need to look up values by a unique key rather than by position.

Example

java
List<Integer> list = new ArrayList<>(); Set<Integer> set = new HashSet<>(); Queue<Integer> queue = new LinkedList<>(); Map<Integer,String> map = new HashMap<>();

Important Point

Picking the right collection up front avoids awkward workarounds later — e.g., using a List and manually checking for duplicates is a sign a Set was the better choice.

Question 3: What is ArrayList?

Ans

ArrayList is a resizable array implementation of the List interface. It provides fast indexed reads and is commonly used when reads are frequent and middle insertions are not dominant.

It grows automatically as elements are added.

Example

java
List<String> names = new ArrayList<>(); names.add("A"); names.add("B"); System.out.println(names.get(0));

Important Point

Removing or inserting elements in the middle can require shifting later elements.

Question 4: What is the difference between HashSet, LinkedHashSet, and TreeSet?

Ans

HashSet stores unique elements with no guaranteed order and offers the fastest average-case operations. LinkedHashSet keeps elements in the order they were inserted, at a small extra memory and performance cost. TreeSet keeps elements sorted according to their natural ordering or a supplied Comparator, with O(log n) operations instead of HashSet's average O(1).

Example

java
Set<Integer> hs = new HashSet<>(List.of(3, 1, 2)); // order not guaranteed Set<Integer> lhs = new LinkedHashSet<>(List.of(3, 1, 2)); // 3, 1, 2 — insertion order Set<Integer> ts = new TreeSet<>(List.of(3, 1, 2)); // 1, 2, 3 — sorted

Important Point

TreeSet requires elements to be Comparable, or a Comparator must be supplied, otherwise it throws a ClassCastException when elements are added.

Question 5: What is the difference between HashMap, LinkedHashMap, and TreeMap?

Ans

HashMap stores key-value pairs with no guaranteed iteration order and the fastest average-case performance. LinkedHashMap preserves insertion order, or optionally access order, which is useful for building an LRU cache. TreeMap keeps entries sorted by key, using natural ordering or a Comparator, with O(log n) operations.

Example

java
Map<String,Integer> lru = new LinkedHashMap<>(16, 0.75f, true); // access-order mode

Important Point

Choose TreeMap only when you actually need sorted iteration — its O(log n) operations are slower than HashMap's average O(1) for plain lookups.

Question 6: What is the difference between HashMap and Hashtable?

Ans

HashMap allows one null key and multiple null values and is not synchronized, making it faster for single-threaded or externally-synchronized use. Hashtable is a legacy class that is fully synchronized and does not permit null keys or null values at all.

Example

java
Map<String,Integer> map = new HashMap<>(); map.put(null, 1); // allowed in HashMap, throws NullPointerException in Hashtable

Important Point

For thread-safe maps in modern code, prefer ConcurrentHashMap over Hashtable — it offers better concurrency without a single global lock.

Question 7: What is a PriorityQueue, and how does it decide ordering?

Ans

A PriorityQueue is a queue where elements are ordered by priority rather than insertion order, by default using their natural ordering via Comparable, or a custom order if a Comparator is supplied, and its head is always the smallest, or highest-priority, element according to that ordering.

Example

java
PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(30); pq.add(10); pq.add(20); System.out.println(pq.poll()); // 10

Important Point

Iterating directly over a PriorityQueue does not produce sorted order — only repeatedly calling poll() retrieves elements in priority order.

Question 8: What is the difference between Iterator and ListIterator?

Ans

Iterator can traverse any Collection, such as a List, Set, or a Map's key/value views, only in the forward direction, and supports removing the current element. ListIterator works only on Lists but can move both forward and backward, and additionally supports adding a new element or replacing the current one during iteration.

Example

java
ListIterator<Integer> it = list.listIterator(); while (it.hasNext()) { int v = it.next(); if (v < 0) it.set(0); // ListIterator can modify during traversal }

Important Point

Both are fail-fast on most standard collections — structurally modifying the underlying collection any other way during iteration throws ConcurrentModificationException.

Question 9: What is the difference between Comparable and Comparator?

Ans

Comparable defines a class's single natural ordering through its own compareTo() method, so the class decides how its instances compare to each other. Comparator defines an external, alternative ordering through compare(), letting different callers sort the same objects in different ways without changing the class itself.

Example

java
class Student implements Comparable<Student> { int marks; public int compareTo(Student o) { return Integer.compare(marks, o.marks); } } students.sort(Comparator.comparing(Student::getName)); // an alternative ordering

Important Point

A class can implement Comparable only once, but you can write as many different Comparators for it as you need.

Question 10: Why must hashCode() be overridden whenever equals() is overridden, and how does this affect HashMap?

Ans

The hashCode contract requires that two objects considered equal by equals() must return the same hash code. HashMap and HashSet rely on hashCode() to decide which bucket an object belongs to, then use equals() to confirm a match within that bucket — if hashCode() isn't consistent with equals(), two "equal" objects could land in different buckets and the map would fail to recognize them as duplicates or fail to find them again.

Example

java
class Point { int x, y; public boolean equals(Object o) { /* compares x and y */ return true; } public int hashCode() { return Objects.hash(x, y); } // must be consistent with equals }

Important Point

Unequal objects are allowed to share the same hash code, called a collision, but equal objects must never have different hash codes.

Question 11: What is LinkedList?

Ans

LinkedList is a doubly linked list implementation that also implements Deque. It stores elements in linked nodes rather than a contiguous dynamic array.

It can be useful for deque operations and specific workloads, but it is not automatically faster than ArrayList for general use.

Example

java
Deque<Integer> q = new LinkedList<>(); q.addFirst(10); q.addLast(20);

Important Point

Indexed access is O(n), so it is usually a poor choice when random index access is frequent.

Question 12: HashMap vs ConcurrentHashMap?

Ans

HashMap is not designed for concurrent structural updates without external synchronization. ConcurrentHashMap supports concurrent access with thread-safe operations and does not allow null keys or values.

Use ConcurrentHashMap when multiple threads need to access and update a shared map safely.

Example

java
ConcurrentHashMap<String,Integer> counts = new ConcurrentHashMap<>(); counts.merge("Java", 1, Integer::sum);

Important Point

Thread-safe does not mean every multi-step business operation becomes automatically atomic; use the appropriate atomic API or synchronization.

Continue Your Preparation