Java Interview Questions - Collections
Here are the most popular Java interview questions about collections.See all questions
Which methods need to be implemented in an object for it to be used as a Key in a HashMap or HashSet? Briefly explain their use. What are the requirements on these methods for the HashMap or HashSet to work correctly?
The two methods required for correctly using any type as a Key in a HashMap or HashSet are hashCode and equals....
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...