Monday, April 19, 2010

Secret of interface Set: It implements

How does set ensures that set doesn't end up adding same object in a set twice. In my previous blog I mentioned about compile time error.

There is another answer to set's ability to maintain uniqueness.

A: Set uses equals method to compare whether two objects are same or not. (Just as you think this fellow is going in correct direction, read next sentence). All set objects have equals method so objects are compared by set itself.

Q: As you mentioned there is "equals" method in Set and then there is also "equals" method in class String. Suppose I create Set of string which of the "equals" method would be used by Set ? The one in Set and the one in String?

A: Set. Set is implemented in such a way that it calls equals method. Since set itself has "equals" method it is called.

Wow ...... Set is implemented such a way.

Q: Suppose I want to create custom Set class. So I create class CustomSet implements Set. What would I have to do in order to check for duplicates in my CustomSet class.

A: Nothing. Set is implemented in such a way that it will call equals method automatically when new item is added into set..

Q: So, nothing needs to be done for new custom class ?
A: (After some thinking) Nothing needs to be done.

Wow !!! Interface Set is implemented such a way that it automatically calls equals method from add method when ever it is implemented. And guess what interfaces implement secretly thing what you would want.

No comments:

Post a Comment