Which is the Best Java Web Framework ?

Java - Collections - Interview Questions and Answers on TreeMap

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 comparator interface used for ?

Ans. The purpose of comparator interface is to compare objects of the same class to identify the sorting order. Sorted Collection Classes ( TreeSet, TreeMap ) have been designed such to look for this method to identify the sorting order, that is why class need to implement Comparator interface to qualify its objects to be part of Sorted Collections.

Q3.  Which are the sorted collections ?

Ans. TreeSet and TreeMap

Q4.  How can we reverse the order in the TreeMap ?

Ans. Using Collections.reverseOrder()

Map<Float,Integer> tree = new TreeMap<Float,Integer>(Collections.reverseOrder());

Q5.  TreeMap orders the elements on which field ?

Ans. Keys

Q6.  How TreeMap orders the elements if the Key is a String ?

Ans. As String implements Comparable, It refers to the String compareTo method to identify the order relationship among those elements.

Q7.  Can we add heterogeneous elements into TreeMap ?

Ans. No, Sorted collections don't allow addition of heterogeneous elements as they are not comparable. 

Q8.  Will it create any problem if We add elements with key as user defined object into the TreeMap ?

Ans. It won't create any problem if the objects are comparable i.e we have that class implementing Comparable interface.

Q9.  Can we have null keys in TreeMap ?

Ans. No, results in exception.

Q10.  Can value be null in TreeMap ?

Ans. Yes.

Q11.  Which interface TreeMap implements ?

Ans. TreeMap implements NavigableMap, SortedMap, Serializable and Clonable.

Q12.  Which of the following collection maintain its elements in Natural Sorted order ? 

 a. HashMap
 b. TreeMap
 c. LinkedHashMap
 d. LinkedMap

Ans. TreeMap

Q13.  If we add Enum constants to a sorted collection ( Treemap , TreeSet ), What will be the order in which they will be maintained ?

 a. Sorted Collection wont maintain them in any order.
 b. Insertion Order
 c. Order in which constants are declared.
 d. Natural Sorting Order.

Ans. Order in which constants are declared.

Q14. Which interfaces are implemented by  TreeMap?


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus


Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.