Monday, May 11, 2009

Java Interview Questions: Collections III

I am writing down some more questions that could come up during an interview. A large number of questions are asked from the Collections API. But, of-course, questions from collections would sometimes require you to be comfortable with other basic Java fundamentals, like over-ridding, over-loading, hashCode(), equals() etc.

Q1. What are hashcodes used for?

Ans. Hash Codes are used for increasing the performance of large collections. The Hash Code value of an object is used by some collection classes. One might think that hash codes are unique, but there can be situations, where the hash codes of different objects become the same. But you really don’t have to bother about this, since the collection classes those use hash codes, provide for a fail-over implementations for such cases.

Q2. What should we keep in mind while over-riding equals() and hashCode()?

Ans. You should over-ride these methods in such a way that when two objects are equal, the hash codes generated for both of them must be equal.

Q2. Is it required that if two objects are not equal, their hash codes will always be different?

Ans. Not necessarily. Think of a situation like this. When you are generating a hash code for a string based on the characters.

ABC‘s hash code = 6 (Add the numeric values of the alphabets)

BAC in such a situation would also have the same hash code. Though, both the strings are different, their hash codes are the same. This design is ok, since both of them will be put into the same bucket, and still you would be able to find them. But, ensuring that, the hash codes of two different objects are never same, will only improve the performance of hash-tables.

Q3. What is a Marker Interface?

Ans. A marker interface is one which doesn’t have any method definitions. For example, Cloneable or Serializable. They are just empty interface definitions. Now, the question is what is the use of such an interface? Here we go. There is a method in the Object class, clone(), which is used to clone objects. So, we should be able to clone any kind of object anywhere. To prevent this, we have Marker Interfaces. Only if we declare that class as implementing the Cloneable, we can clone the objects of that class, else we will get an exception. Thus, implementing Cloneable class, which is a marker interface, just tags that class as “Hey, You can clone me know”. And the clone() method will not throw any exception. Same is the case with Serializable. If the class is not implementing the Serializable interface, any attempt to write the Object/ or serialize it will fail.

Q4. What are the different Marker Interfaces?

Ans. Cloneable, Serializable, EventListener,

3 comments:

Anonymous said...
This comment has been removed by the author.
Anonymous said...

nice explanation to the questions. Another links which could be helpful for all is
Java Questions

Unknown said...

Nice collection of questions.