Java - Collections - Interview Questions and Answers on Map

Q1.  Difference between TreeMap and HashMap ?

Ans. They are different the way they are stored in memory. TreeMap stores the Keys in order whereas HashMap stores the key value pairs randomly.

Q2.  What is the difference between List, Set and Map ?

Ans. List - Members are stored in sequence in memory and can be accessed through index.
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates. Map - Contains Key , Value pairs.

Q3.  Which interface does java.util.Hashtable implement?

Ans. Java.util.Map

Q4.  Which interface provides the capability to store objects using a key-value pair?

Ans. Java.util.Map

Q5.  Difference between HashMap and Hashtable?

Ans. Hashtable is synchronized whereas HashMap is not.

HashMap allows null values whereas Hashtable doesn’t allow null values.

Q6.  There are two objects a and b with same hashcode. I am inserting these two objects inside a hashmap.



hMap.put(a,a);

hMap.put(b,b);



where a.hashCode()==b.hashCode()




Now tell , how many objects will be there inside the hashmap?


Ans. There can be two different elements with the same hashcode. When two elements have the same hashcode then Java uses the equals to further differentation. So there can be one or two objects depending on the content of the objects.

Q7.  Can we create a null as a key for a map collection ?

Ans. Yes , for Hashtable.

Q8.  What is the use of hashcode in Java ?

Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.

Q9.  Difference between Map and HashMap ?

Ans. Map is an interface where HashMap is the concrete class.

Q10.  What is a Property class ?

Ans. The properties class is a subclass of Hashtable that can be read from or written to a stream.