Here are some more interview questions on Collections. Recently, I had an interview in which these were asked. Well, I couldn't answer all of them. Check how many you know.
1. What is the difference between Comparator and Comparable?
Ans. Both interfaces are used to sort a list or a collection of objects. However, to implement a Comparable, a class must implement a single method compareTo(anotherObj). By doing this, you can sort a class accordingly whatever you have implemented in this method, i.e, perhaps only on a single criteria. Only one sort sequence can be created and you have to modify the class whose instances you want to sort. Through Comparable, you can compare the instances of the same class, since the logic is written inside the class itself. “The comparable interface should be used when the current object is to be compared to objects of its type only.”
The Comparator interface gives you the extra feature of sorting your collection in any number of ways. Here also, we have to implement only one method, i.e, compare(objOne,objTwo). Here, many sort sequences can be created. Instead of making changes to the class, you define a separate class from the class whose instances you want to sort. Thus, a Comparator can compare two objects(any objects for that matter) and return the result based on the criteria imposed by the Comparator. “The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn't know how to compare the objects and expects you to give it.”
2. Does a HashMap allow null as a key and value?
Ans. Yes, you can put a null as a key, and values as null as well. Whereas, Hashtable doesn’t allow anything as null, neither a key or a value. The point of allowing a null as key is not clear though.