🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Let's begin.
1. Explain the internal working of HashMap in Java.
HashMap stores data in key–value pairs and internally uses an array of buckets.
When you put an entry into a HashMap, the key’s hash code is first calculated. This hash code is then transformed into an index that points to a specific bucket in the internal array.
Each bucket can hold multiple entries. Initially, each bucket behaves like a linked structure where entries are connected in sequence.
When a key–value pair is added, HashMap checks whether the bucket already contains entries. If the bucket is empty, the entry is stored directly. If not, HashMap compares keys to decide whether to replace an existing value or add a new entry.
Retrieval works the same way. The key’s hash code determines the bucket, and then equals comparison is used to find the exact entry inside that bucket.
Interviewers ask this question to test understanding of hashing, indexing, and collision handling.
A strong answer explains that HashMap performance depends on good hash code distribution. Poor hash codes cause too many entries in one bucket, degrading performance.
This internal design allows HashMap to provide fast access in most real-world scenarios.
2. What happens when two keys have the same hash code?
When two keys have the same hash code, a hash collision occurs.
In this case, both keys are mapped to the same bucket in the HashMap. HashMap does not rely only on the hash code. It also uses the equals method to distinguish between keys.
When inserting the second key, HashMap checks existing entries in the bucket. If equals returns true, the value is replaced. If equals returns false, the new entry is added to the bucket.
During retrieval, HashMap again calculates the hash code, goes to the same bucket, and then iterates through entries using equals to find the correct key.
Interviewers often trap candidates by asking whether same hash code means same object. It does not. Hash codes can be equal while objects are different.
A strong answer explains that proper implementation of both hashCode and equals is critical. If equals is not implemented correctly, HashMap behavior becomes unpredictable.
Understanding collision handling is essential for writing correct and performant Java applications.
3. What changes were introduced in HashMap in Java 8?
Java 8 introduced an important improvement to HashMap to handle excessive collisions.
Before Java 8, buckets used only linked structures. In worst-case scenarios, this caused performance to degrade significantly.
In Java 8, when the number of entries in a bucket crosses a threshold, the bucket structure is transformed into a balanced tree.
This change improves lookup performance from linear time to logarithmic time in heavily collided buckets.
Interviewers often ask this question to check whether candidates understand performance evolution, not just syntax.
This change made HashMap much more resilient to poor hash distributions and malicious inputs.
A strong answer explains that Java 8 improved worst-case performance while keeping average performance fast.
This shows that Java collections continuously evolve to handle real-world scalability and security challenges.
4. How does ConcurrentHashMap improve performance in a multi-threaded environment?
ConcurrentHashMap is designed specifically for high-concurrency scenarios.
Unlike HashMap, it allows multiple threads to read and write concurrently without blocking the entire structure.
Instead of locking the whole map, ConcurrentHashMap uses fine-grained locking and non-blocking techniques. This allows multiple threads to operate on different parts of the map at the same time.
Read operations are mostly lock-free, which significantly improves performance in read-heavy workloads.
Interviewers ask this question to see whether candidates understand that thread safety alone is not enough. Performance under concurrency matters.
ConcurrentHashMap avoids common bottlenecks seen in synchronized maps. This makes it suitable for caching, shared state, and high-throughput systems.
A strong answer explains that ConcurrentHashMap balances safety and scalability, making it ideal for modern multi-core applications.
5. What is the internal difference between HashMap and ConcurrentHashMap?
HashMap is not thread-safe and does not provide any synchronization.
ConcurrentHashMap, on the other hand, is built for concurrent access. Its internal design allows multiple threads to read and update the map safely.
HashMap uses a single internal structure without any concurrency control. If accessed by multiple threads without synchronization, it can lead to data corruption.
ConcurrentHashMap uses advanced concurrency techniques to reduce contention. It avoids locking the entire map, allowing higher throughput.
Interviewers often check whether candidates understand why synchronized HashMap is not enough. Synchronization blocks all access, hurting scalability.
A strong answer explains that ConcurrentHashMap is not just a thread-safe HashMap, but a carefully designed data structure optimized for concurrency.
This distinction is crucial when designing high-performance, multi-threaded Java systems.
6. Name the algorithms used by Arrays.sort() and Collections.sort().
Arrays.sort() and Collections.sort() use different sorting strategies depending on the data type being sorted.
For primitive arrays, Arrays.sort() uses a highly optimized Dual-Pivot Quicksort. This algorithm is fast in practice, uses less memory, and performs very well for large primitive datasets. It is not stable, but stability is usually not required for primitives.
For object arrays, Arrays.sort() uses TimSort, which is a hybrid sorting algorithm derived from merge sort and insertion sort. TimSort is stable and performs exceptionally well on partially sorted data.
Collections.sort() internally converts the collection into an array and then delegates sorting to Arrays.sort(). This means it also uses TimSort for object sorting.
Interviewers often ask this question to see whether candidates know that Java uses different algorithms for primitives and objects.
A strong answer explains that algorithm choice depends on stability requirements, memory usage, and real-world performance characteristics.
This shows awareness of Java’s internal optimizations rather than just API usage.
7. When should TreeSet be preferred over HashSet?
TreeSet should be preferred over HashSet when sorted order or range-based operations are required.
HashSet stores elements without any guaranteed order. It is optimized for fast insertion and lookup but does not maintain sorting.
TreeSet, on the other hand, stores elements in a sorted structure. Elements are ordered either by their natural ordering or by a custom comparator.
If your application needs operations like finding the smallest element, largest element, or retrieving a subset within a range, TreeSet is the correct choice.
Interviewers often check whether candidates understand the performance trade-off. HashSet provides faster average performance, while TreeSet has slightly slower operations due to maintaining order.
TreeSet is also useful when predictable iteration order is required. HashSet does not guarantee any consistent iteration order.
A strong answer explains that TreeSet trades speed for ordering and should be used only when ordering or range queries are necessary.
8. Why is HashMap not thread-safe?
HashMap is not thread-safe because it does not provide any synchronization for concurrent access.
If multiple threads modify a HashMap at the same time without proper synchronization, its internal structure can become corrupted. This can lead to data inconsistency, infinite loops, or lost updates.
HashMap is designed for single-threaded or externally synchronized use cases. Adding built-in synchronization would slow down performance for the majority of use cases where concurrency is not required.
Interviewers often ask this question to see whether candidates understand the difference between thread safety and performance.
Using a synchronized wrapper around HashMap makes it thread-safe but significantly reduces concurrency because it locks the entire map.
Modern applications prefer specialized concurrent collections that are designed for multi-threaded access without heavy locking.
A strong answer explains that HashMap’s lack of thread safety is a deliberate design decision focused on speed and simplicity.
9. How does resizing work in HashMap?
HashMap resizes when the number of entries exceeds a certain threshold.
This threshold is calculated using the current capacity and a load factor. When the map grows beyond this limit, resizing is triggered to maintain efficient access.
During resizing, a new internal array with larger capacity is created. Existing entries are then re-distributed into the new array based on their hash values.
This process is expensive because all entries must be reprocessed. That is why frequent resizing can impact performance.
Interviewers often test whether candidates understand why choosing an appropriate initial capacity matters.
By setting an initial capacity close to the expected number of entries, developers can reduce the number of resizing operations.
A strong answer explains that resizing is essential for maintaining performance but should be minimized through proper configuration and capacity planning.
10. What happens if a mutable object is used as a HashMap key?
Using a mutable object as a HashMap key is dangerous and can break map behavior.
HashMap relies on the key’s hash code and equality to store and retrieve values. If a key’s internal state changes after insertion, its hash code may change.
When this happens, the entry may end up in the wrong bucket. As a result, retrieving the value using the same key may fail even though the entry exists in the map.
Interviewers ask this question to test understanding of hashing contracts. Keys must be immutable or at least not modified while used in a map.
This issue can lead to memory leaks, incorrect behavior, and very hard-to-debug problems.
A strong answer explains that keys should be immutable and must have stable hash code and equals behavior throughout their lifetime in the map.
This rule is fundamental for using hash-based collections safely and correctly.
11. What is the difference between HashSet and TreeSet?
HashSet and TreeSet are both implementations of the Set interface, but they differ in ordering, performance, and internal structure. HashSet stores elements using a hash table and does not maintain any order. Its primary advantage is fast performance for add, remove, and lookup operations, typically running in constant time.
TreeSet stores elements in a sorted order using a red-black tree data structure. Elements are arranged based on their natural ordering or a custom comparator. Because of sorting, operations in TreeSet generally take logarithmic time, making it slower than HashSet.
HashSet allows one null element, while TreeSet does not allow null values because comparison is required for sorting. TreeSet is commonly used when sorted output is needed, such as maintaining sorted names, timestamps, or rankings.
In interviews, the key takeaway is that HashSet focuses on performance, while TreeSet focuses on sorted data.
12. What is the difference between Comparable and Comparator?
Comparable and Comparator are both used for sorting objects in Java, but they differ in how and where the sorting logic is defined. Comparable is an interface that is implemented by the class whose objects need to be sorted. It defines the compareTo method, which provides a single natural ordering for objects.
Comparator is a separate interface used to define custom sorting logic outside the class. It provides the compare method and allows multiple sorting strategies for the same class. This is useful when objects need to be sorted based on different attributes.
Comparable is suitable when a class has a default sorting behavior, such as sorting numbers or strings. Comparator is preferred when sorting logic should not modify the class or when multiple sorting orders are required.
In interviews, it is important to highlight that Comparator offers more flexibility and better separation of concerns.
13. What is Iterator and how is it different from ListIterator?
Iterator is an interface used to traverse elements of a collection one by one. It supports forward-only traversal and provides methods to check for the next element and remove the current element safely during iteration. Iterator works with all Collection types.
ListIterator is a more powerful iterator that works only with List implementations. It supports both forward and backward traversal, allowing movement in both directions. It also provides methods to add, replace, and retrieve the index of elements during iteration.
Iterator is commonly used when simple traversal is required, while ListIterator is used when more control over iteration is needed, such as modifying elements while iterating or traversing in reverse order.
In interviews, you should mention that ListIterator is bidirectional and supports modification operations, whereas Iterator is unidirectional and more generic.
14. What is fail-fast and fail-safe behavior in Java collections?
Fail-fast and fail-safe describe how iterators behave when a collection is modified during iteration. Fail-fast iterators immediately throw a ConcurrentModificationException if the collection is structurally modified outside the iterator. This helps detect programming errors early.
Most collection classes such as ArrayList, HashMap, and HashSet use fail-fast iterators. They work by maintaining a modification count and checking it during iteration. If a mismatch is detected, the exception is thrown.
Fail-safe iterators, on the other hand, do not throw exceptions when the collection is modified. They work on a cloned copy of the collection, so changes to the original collection do not affect iteration.
Concurrent collections like ConcurrentHashMap use fail-safe behavior. In interviews, highlight that fail-fast focuses on correctness, while fail-safe focuses on concurrency support.
15. What is the difference between HashMap and LinkedHashMap?
HashMap and LinkedHashMap both store key-value pairs, but they differ in ordering behavior. HashMap does not guarantee any order of keys or values. The iteration order may change over time as elements are added or removed.
LinkedHashMap maintains insertion order by default. It internally uses a doubly linked list along with a hash table. This makes iteration predictable and consistent. LinkedHashMap can also be configured to maintain access order, which is useful for implementing LRU caches.
HashMap generally performs slightly better due to lower overhead. LinkedHashMap consumes more memory because of additional links between entries.
In interviews, mention that HashMap is preferred for performance, while LinkedHashMap is chosen when ordering or caching behavior is required.
16. What is the difference between HashMap and TreeMap?
HashMap and TreeMap are Map implementations that differ mainly in ordering and performance. HashMap does not maintain any order of keys and provides fast access with constant-time performance for most operations.
TreeMap stores keys in a sorted order using a red-black tree. Keys are sorted based on natural ordering or a custom comparator. Because of sorting, operations in TreeMap take logarithmic time.
HashMap allows one null key, whereas TreeMap does not allow null keys because comparison is required. TreeMap is useful when range-based queries or sorted traversal is required.
In interviews, emphasize that HashMap is best for fast lookups, while TreeMap is chosen when sorted keys or ordered traversal is important.
17. Why is the equals and hashCode contract important in Java collections?
The equals and hashCode contract is critical for collections that rely on hashing, such as HashMap and HashSet. According to the contract, if two objects are equal according to equals, they must return the same hashCode.
Hash-based collections first use the hashCode to determine the bucket location. Then equals is used to check for actual equality. If this contract is violated, objects may be stored in incorrect buckets, causing unexpected behavior like duplicate entries or failed lookups.
For example, if equals is overridden but hashCode is not, two logically equal objects may end up in different buckets. This breaks the collection’s integrity and leads to hard-to-debug issues.
In interviews, you should stress that immutable fields should be used in equals and hashCode implementations to prevent changes after insertion. Proper implementation ensures correctness, performance, and reliability of Java collections.
18. What is the difference between immutable and unmodifiable collections?
Immutable collections cannot be changed after creation. Once created, their state remains fixed, and any modification attempt results in a new collection or an exception. This makes immutable collections inherently thread-safe.
Unmodifiable collections, on the other hand, are read-only views of an existing collection. The underlying collection can still be modified through another reference, and those changes are reflected in the unmodifiable view.
Java provides unmodifiable collections through utility methods like those in the Collections class. Immutable collections are provided through factory methods introduced in newer Java versions.
In interviews, highlight that immutability guarantees safety and predictability, while unmodifiable collections only restrict access through a specific reference. This distinction is crucial when designing concurrent and secure applications.
19. What is WeakHashMap, and when should it be used?
WeakHashMap is a special Map implementation where keys are stored using weak references. This means that if a key is no longer strongly referenced elsewhere in the application, it becomes eligible for garbage collection.
Once the garbage collector removes a key, the corresponding entry is automatically removed from the map. This makes WeakHashMap useful for memory-sensitive applications.
WeakHashMap is commonly used for caching metadata, listeners, or temporary mappings where entries should not prevent garbage collection. It helps avoid memory leaks that can occur with regular HashMap.
However, WeakHashMap is not thread-safe and should be used carefully in concurrent environments. In interviews, emphasize that WeakHashMap is designed for automatic memory cleanup rather than performance or ordering guarantees.
20. How does PriorityQueue work internally in Java?
PriorityQueue in Java is implemented using a binary heap data structure. By default, it follows natural ordering, but a custom comparator can also be provided.
The smallest element is always placed at the head of the queue. Insertions and removals are performed in logarithmic time to maintain the heap property. Unlike sorted collections, PriorityQueue does not guarantee full ordering during iteration.
PriorityQueue allows duplicate elements but does not allow null values. It is commonly used in scheduling systems, task prioritization, and algorithms like Dijkstra’s shortest path.
In interviews, mention that PriorityQueue is optimized for retrieving the highest or lowest priority element efficiently, not for ordered traversal. Understanding this distinction demonstrates strong knowledge of Java collection internals.
21. What is CopyOnWriteArrayList and when should it be used?
CopyOnWriteArrayList is a thread-safe variant of ArrayList designed for concurrent read-heavy environments. Instead of locking during updates, it creates a new copy of the underlying array for every modification.
This design allows multiple threads to read the list simultaneously without synchronization, providing excellent read performance. Iterators are fail-safe and do not throw ConcurrentModificationException.
However, write operations are expensive due to array copying. Therefore, CopyOnWriteArrayList is not suitable for write-heavy applications.
In interviews, emphasize that CopyOnWriteArrayList is ideal when reads significantly outnumber writes, such as configuration data or event listeners. It trades memory and write cost for simplicity, safety, and predictable iteration behavior.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment