Monday, May 4, 2009

Java Interview Questions: Collections II

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.


Anonymous said...

Good collection of questions. Very descriptive and easy to understand.


viaam said...

Nice blog ! I like your article and i would like to read it again..It is beneficial both for young graduates as well as for freshers.Thank you Emily for the interview question. I’ll add it to our list
For number one quality bag in which You will get quality as well as fashion.

bag manufacturers

javin paul said...

Nice questions and thanks for sharing. I have also shard my favorites as Top 10 Java Collection Interview Questions Answers . let me know how do you find it.

Java Discover said...

Hi All,
Get your set of Java Collection interview questions here -

Java Discover said...

for more java interview questions -