Top 15 Collections Framework Interview Questions for Java Developers[2023–24]

Ajay Rathod
11 min readNov 12, 2023

--

Ajay Rathod

Hello Guys, in this article I will be posting the top 15 collection framework interview questions that are important in Java dev interviews. please make a note of it.

Are you preparing for a job interview as a Java developer?

Find my books:

Guide To Clear Java Developer Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).

Guide To Clear Spring-Boot Microservice Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).

Guide To Clear Front-End Developer Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).

Download the sample copy here:

Guide To Clear Java Developer Interview[Free Sample Copy]

Guide To Clear Spring-Boot Microservice Interview[Free Sample Copy]

Guide To Clear Front-End Developer Interview [Sample_Copy]

Ready for personalized guidance? Book your 1-on-1 session with me here: https://topmate.io/ajay_rathod11

Introduction

“In Java interviews, you will undoubtedly encounter questions about the core Java language and its various frameworks. Among these, the Java Collections Framework holds significant importance. Failure to grasp and articulate the concepts of this framework can lead to rejection, as it serves as a crucial indicator of your Java expertise.

Therefore, it is highly recommended to develop a solid understanding of the Java Collections Framework before attending an interview. Let’s delve into this,

Common questions for beginners can start by explaining what the collection hierarchy is, I have posted one pic where it is mentioned.

I am covering below topics:

  1. Hashmap
  2. concurrent-hashmap
  3. Equality
  4. Iterators
  5. ArrayList
  6. LinkedList
  7. Set

What is the difference between HashMap vs HashTable, which one is synchronized?

What difference between Hashmap vs concurrent hashmap and the follow-up question on how they work internally etc?

How does hashmap work internally? (IMP)

A hashmap is a data structure that stores key-value pairs. It is implemented using a hash table, which is an array of buckets. Each bucket contains a linked list of key-value pairs.

When you add a new key-value pair to a hashmap, the hash function is used to calculate the bucket index for the key. The key-value pair is then added to the linked list in the corresponding bucket.

When you retrieve a value from a hashmap, the hash function is again used to calculate the bucket index for the key. The linked list in the corresponding bucket is then searched for the key-value pair with the matching key. If the key-value pair is found, the value is returned. Otherwise, null is returned.

Hashmaps are very efficient for storing and retrieving data, because they can find a key-value pair in constant time, on average. However, they can be inefficient for large datasets, because they require a lot of memory to store the hash table.

How to create a custom hashmap of size 2GB? (for Experienced candidates)

It’s a bad design. Having 1.7GB of data in memory on a HashMap, I would have done any of the two:

  1. Persist all the data (file/database) and have the top 1% or something in memory. Use some algorithm for deciding which IDs will be in memory and when.
  2. Use Memcached. The easiest way out. An in-memory distributed hashable. This is exactly what DHTs are used for.

But to create a hashmap you can use these two,

  1. Array -This is the simplest approach, but it can be inefficient for large hashmaps, as it requires a lot of memory
  2. LinkedList -This approach is more efficient for large hashmaps, as it does not require as much memory.

Can we insert Null in Concurrent Hashmap?

Inserting null objects is not possible in ConcurrentHashMap as a key or value.

Can we insert the null key in the hashmap and hashtable?

Hashtable does not allow null keys but HashMap allows one null key and any number of null values

Internal implementation of Concurrent HashMap?

ConcurrentHashMap is a hash-based concurrent map that aims to provide high concurrency update performance and good scalability. It uses a segmented lock-free approach to achieve concurrent access.

Internally, ConcurrentHashMap is implemented as an array of segments, where each segment is a separate hash table. Each segment is locked independently, which allows multiple threads to concurrently modify different segments of the map without blocking each other.

When a thread needs to modify the map, it first finds the segment that contains the key it wants to modify. The thread then locks the segment and modifies the hash table accordingly. Once the modification is complete, the thread unlocks the segment.

What are fast and fail-safe examples in the collections framework?

Fail-fast and fail-safe iterators are two different types of iterators that handle concurrent modifications to a collection differently.

  • Fail-fast iterators throw a ConcurrentModificationException if the collection is modified while the iterator is in use. This is because fail-fast iterators rely on the collection's modCount field to detect modifications. If the modCount changes while the iterator is in use, the iterator knows that the collection has been modified and throws an exception.
  • Fail-safe iterators do not throw an exception if the collection is modified while the iterator is in use. This is because fail-safe iterators typically work on a copy of the collection, rather than the collection itself. As a result, modifications to the original collection do not affect the iterator.

Fail-fast iterators are typically faster than fail-safe iterators because they do not need to make a copy of the collection. However, fail-safe iterators are more robust to concurrent modifications.

Here are some examples of fail-fast and fail-safe iterators in Java:

  • Fail-fast iterators: ArrayList, HashMap, HashSet
  • Fail-safe iterators: CopyOnWriteArrayList, ConcurrentHashMap, ConcurrentSkipListSet

In general, you should use a fail-fast iterator if you do not expect the collection to be modified while the iterator is in use. If you do expect the collection to be modified, you should use a fail-safe iterator.

  • Use ArrayList when you need to store a list of names and you need to be able to access any name in the list quickly.
  • Use LinkedList when you need to store a list of items that you need to frequently add or remove from the beginning or end of the list, such as a queue.

How to create an immutable map in Java?

In Java, you can create an immutable map using the Collections class. Here are the steps to create an immutable map:

Create a map with the desired key-value pairs:

Map<String, Integer> mutableMap = new HashMap<>();
mutableMap.put("apple", 1);
mutableMap.put("banana", 2);
mutableMap.put("orange", 3);

Use the Collections.unmodifiableMap() method to create an immutable map from the mutable map:

Map<String, Integer> immutableMap = Collections.unmodifiableMap(mutableMap);

Note that any attempt to modify the immutableMap will result in an UnsupportedOperationException. For example, the following code will throw an exception:

immutableMap.put("grape", 4); // This will throw an UnsupportedOperationException

What's the difference between a List and a Set?

In Java, both List and Set are interfaces that represent collections of objects, but they differ in their behavior and characteristics.

  1. Order: List is an ordered collection of elements, where the order of the elements is determined by their position in the list. Set, on the other hand, is an unordered collection of elements, where the order of the elements is not defined.
  2. Duplicates: List can contain duplicates, i.e., it allows multiple occurrences of the same element. Set does not allow duplicates, i.e., it only contains unique elements.
  3. Implementation: List is typically implemented as an array or a linked list, while Set is typically implemented as a hash table or a tree.
  4. Access: List provides access to elements based on their index, i.e., you can retrieve elements from a list by specifying their position in the list. Set does not provide direct access to elements based on their index, i.e., you cannot retrieve elements from a set by specifying their position in the set.
  5. Performance: List provides efficient random access to elements, but may be slower when it comes to searching for elements or removing elements. Set is optimized for fast searching and removal of elements, but may be slower when it comes to random access to elements.

What is the difference between Hashmap and LinkedHashmap?

Both HashMap and LinkedHashMap are implementations of the Map interface in Java, but they differ in their underlying data structure and the order in which they store the entries.

HashMap uses a hash table to store its entries, which provides constant-time performance for the basic operations (get, put, and remove), on average. The order in which the entries are stored in a HashMap is not predictable and is based on the hash code of the keys.

LinkedHashMap, on the other hand, extends HashMap and maintains a doubly-linked list of the entries in the order in which they were inserted. This allows for predictable iteration order and provides constant-time performance for the basic operations, but with a slightly higher overhead due to the maintenance of the linked list.

Why Hashmap does not maintain the order like Linkedhashmap?

HashMap does not maintain the order of its entries because it uses a hash table to store its entries. The hash table works by using a hash code of the key to determine the bucket (or index) where the entry should be stored. The hash function distributes the keys randomly across the buckets, and the order of the keys in the hash table depends on the hash codes of the keys.

The hash table’s primary advantage is that it provides constant-time performance for the basic operations of get, put, and remove, on average, regardless of the size of the hash table. However, the disadvantage of the hash table is that it does not maintain the order of the keys or the entries.

On the other hand, LinkedHashMap maintains the order of its entries by maintaining a doubly-linked list that runs through all the entries in the order in which they were inserted. This linked list imposes an order on the entries that are independent of their hash codes and allows for predictable iteration order.

How Linkedhashmap is able to maintain the insertion order?

LinkedHashMap maintains the insertion order of its entries by using a doubly-linked list that runs through all the entries in the order in which they were inserted.

When a new entry is added to a LinkedHashMap, it is added to the end of the linked list. This ensures that the most recently added entry is always the last one on the list. When an entry is accessed, it is moved to the end of the list to ensure that it remains the last one in the list. This guarantees that the order of entries is preserved based on their insertion order.

When an entry is removed, the linked list is updated to remove the entry from the list, and the previous and next entries in the list are linked directly to each other. This ensures that the order of the remaining entries is preserved.

The linked list is maintained by each entry in the map holding a reference to the previous and next entries in the list. This allows the LinkedHashMap to traverse the list quickly and efficiently.

Java 8 changes in Hashmap? (This question is still asked to know if we are updated or not). How Hashmap performance is improved, and what improvements are there?

In Java 8, HashMap has introduced a new approach for resolving hash code collisions called the "balanced tree" approach. This approach is used when the number of entries in a bucket exceeds a certain threshold (currently set to 8). In this case, instead of using a linked list to store the entries in the bucket, HashMap will convert the bucket into a balanced tree structure.

Here are some key points related to hash code collisions and the balanced tree approach in HashMap in Java 8:

  1. Prior to Java 8, HashMap used a linked list to store the entries in a bucket that had hash code collisions. This approach could result in poor performance for large maps with many hash code collisions, as the time required to search the linked list increased linearly with the number of entries in the list.
  2. In Java 8, if the number of entries in a bucket exceeds a certain threshold (currently set to 8), HashMap will convert the bucket into a balanced tree structure. This approach provides better performance for large maps with many hash code collisions, as the time required to search a balanced tree is logarithmic in the number of entries.
  3. The balanced tree approach requires that the keys in the map implement the Comparable interface or that a Comparator is provided to the HashMap constructor. This is because the tree structure requires a total ordering of the keys to maintain the balance of the tree.
  4. The balanced tree approach is only used for buckets that have hash code collisions and have exceeded the threshold. Buckets with fewer than 8 entries will continue to use a linked list.
  5. The threshold value of 8 is chosen based on performance testing and may be adjusted in future releases of Java if necessary.

How to compare the equality of two customized objects in Java?

To compare the equality of two customized objects in Java, you need to override the equals() method and the hashCode() method. Here's how you can do it:

  1. Override the equals() method:
  • In your custom class, override the equals() method inherited from the Object class.
  • Inside the equals() method, compare the fields of the two objects to determine if they are equal.
  • Return true if the fields are equal, and false otherwise.
  • Ensure to follow the general contract of the equals() method, which includes checking for null, comparing types, and comparing individual fields.

Conclusion

The collections framework is an important topic don't skip this if you are going for an interview.

Please subscribe to my channel here — Ajay Rathod

Going forward I will be adding stories on my channel, this will be more interactive, fun, short, and crisp.

Articles you may like

Free Sample copies on Core Java, Spring-boot Microservice, and SQL

Core-Java : Grokking the Java Interview [Free Sample Copy] , Grokking the Java Interview Vol 2 [Free Sample Copy]

Spring-Boot : Grokking the Spring Boot Interview [Free Sample Copy]

SQL: Grokking the SQL Interview [Free Sample Copy]

Thanks for reading

  • 👏 Please clap for the story and subscribe 👉(you can give upto 50 likes)
  • 📰 Read more content on my Medium (40+ stories on Java Developer interview)

Find my books:

--

--

Ajay Rathod
Ajay Rathod

Written by Ajay Rathod

Java Programmer | AWS Certified | Writer | Find My Books on Java Interview here - https://rathodajay10.gumroad.com | YouTube - https://www.youtube.com/@ajtheory

Responses (1)