Java Collections Interview Questions and Answers
The Java Collections Framework (JCF) is one of the most heavily tested topics in Java software engineering interviews. Whether you are interviewing for backend microservices, enterprise applications, or distributed systems roles, a deep understanding of collection hierarchies, interface contracts, internal memory layouts, and concurrency models is essential.
This comprehensive guide explores the most frequently asked Java Collections interview questions, complete with deep-dive technical explanations and production-grade code examples.
1. What is the difference between Collection and Collections in Java?
java.util.Collection is the root interface of the Java Collections hierarchy. It defines core methods common to all collections such as add(), remove(), size(), and iterator(). Sub-interfaces like List, Set, and Queue extend this interface.
java.util.Collections is a utility class consisting exclusively of static methods that operate on or return collections. It provides algorithms for sorting (Collections.sort()), searching (Collections.binarySearch()), synchronization wrappers (Collections.synchronizedList()), and unmodifiable collections (Collections.unmodifiableMap()).
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> frameworkList = new ArrayList<>();
frameworkList.add("Spring Boot");
frameworkList.add("Quarkus");
frameworkList.add("Micronaut");
// Using java.util.Collections utility class to sort
Collections.sort(frameworkList);
// Creating an unmodifiable thread-safe view
List<String> readOnlyList = Collections.unmodifiableList(frameworkList);
System.out.println("Sorted Frameworks: " + readOnlyList);
}
}
2. Explain the internal working of HashMap in Java. How are hash collisions handled?
HashMap stores key-value pairs as internal Node<K, V> objects inside an array of buckets. When a key is inserted, Java computes its hash using hashCode() and applies a perturbation function to spread bits. The resulting hash is mapped to a bucket index using the bitwise operation (n - 1) & hash, where n is the capacity of the array.
Collision Handling: Prior to Java 8, collisions were resolved exclusively using linked lists per bucket, resulting in O(N) worst-case lookup times. Since Java 8, if a bucket exceeds a threshold (TREEIFY_THRESHOLD = 8) and the total table capacity is at least 64, the linked list is automatically converted into a self-balancing Red-Black Tree, improving worst-case search time from O(N) to O(log N).
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> cache = new HashMap<>();
cache.put("DatabaseConnectionPool", 10);
cache.put("ThreadPoolSize", 50);
// Accessing O(1) average time complexity
System.out.println("Connection Pool Limit: " + cache.get("DatabaseConnectionPool"));
}
}
3. What is the contract between hashCode() and equals() in Java?
The contract between hashCode() and equals() in java.lang.Object is crucial when using objects as keys in hash-based collections (HashMap, HashSet):
- If two objects are equal according to the
equals(Object)method, callinghashCode()on each must produce the exact same integer result. - If two objects have unequal hash codes (
hashCode()does not match), they are guaranteed not to be equal according toequals(). - If two objects have the same hash code, they are not required to be equal (this is known as a hash collision).
Violating this contract causes hash-based collections to fail when attempting to retrieve stored objects because keys cannot be located in their correct buckets.
4. What is the difference between Comparable and Comparator?
Comparable is used to define the natural ordering of an object. The class itself must implement the compareTo(T o) method. It is intrusive because modifying the class code is required.
Comparator is used to define custom external ordering. It is implemented in a separate class or lambda expression with the compare(T o1, T o2) method, allowing multiple sorting strategies without modifying the original class.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class ServerNode {
String host;
int latency;
ServerNode(String h, int l) { host = h; latency = l; }
}
public class ComparatorExample {
public static void main(String[] args) {
List<ServerNode> servers = new ArrayList<>();
servers.add(new ServerNode("us-east", 45));
servers.add(new ServerNode("eu-central", 12));
// Custom Comparator sorting by latency ascending using lambda
servers.sort(Comparator.comparingInt(s -> s.latency));
System.out.println("Fastest Server: " + servers.get(0).host);
}
}
Conclusion
Mastering the Java Collections Framework—including HashMap treeification internals, equals/hashCode contracts, and sorting strategies—is essential for clearing technical interviews and engineering high-performance Java applications.