Java - Interview Questions and Answers on Sorting

Q1.  What is the difference between comparable and comparator in java.util pkg?

Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data member where as comparator interface is used to sort the object based on multiple data members.

Q3.  What is Comparable Interface?

Ans. It is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered.

Q4.  What are the difference between ArrayList and LinkedList from the perspective of Sorting ?

Ans. Initial sorting could be pain but lateral addition of elements in a sorted list is good with linked list. ArrayList are good with initial sorting but are pain when it comes to adding elements in the sorted list.

Q5.  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.

Q6.  Which are the sorted collections ?

Ans. TreeSet and TreeMap

Q7.  Can we add heterogeneous elements into TreeMap ?

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

Q10.  If I try to add Enum constants to a TreeSet, What sorting order will it use ?

Ans. Tree Set will sort the Values in the order in which Enum constants are declared.

Q11.  Can we override compareTo method for Enumerations ?

Ans. No. compareTo method is declared final for the Enumerations and hence cannot be overriden. This has been intentionally done so that one cannot temper with the sorting order on the Enumeration which is the order in which Enum constants are declared.

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

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

Ans. TreeMap

Q15.  Collections.sort can only be performed on ..

 a. Set
 b. List
 c. Map
 d. Any Collection implementation

Ans. List

Q16.  Which sorting algorithm is used by Collections.sort() in Java ?

Ans. The sorting algorithm is a modified mergesort. This algorithm offers guaranteed n log(n) performance.