Java Interview Questions - Collections

Here are the most popular Java interview questions about collections.

See all questions

What Collection would you use to iterate with insertion order and also have O(1) lookup time? Are there any drawbacks to using this Collection?

LinkedHashSet provides an average O(1) lookup time and also maintains the entries in a doubly-linked list, which can be used to maintain insertion order. The only drawback in this case is that we cannot have duplicates in the Collection because it is a Set.

What happens when one thread modifies a HashMap while another thread is iterating the same map? What is the correct way to do this?

A HashMap is not a synchronized Map, meaning that it is not thread-safe. If a HashMap is modified by a thread while another thread is iterating it, a ConcurrentModificationException will be thrown.

There are two possible ways to do this correctly:


Does a HashMap Key object have to be Immutable?

HashMap calculates the location of an object based on the value of the hashCode function. If the values used to calculate the hashCode of an object change after it is inserted in the HashMap, this will result in the Key returning a different address than the one originally used. In this case, the HashMap cannot locate the original Key and the objec


Looking for developers?

Want to learn more about Gigster? Enter your email and one of our project engineers will be in touch.