Monday, March 30, 2009

Why Set collection has no get method?

It's a interseting question.

When we are developing a tool (kind of crawler), we had this requirement.

We used our own object and over ride the equals method. We were abou to use the get method in the set and finally realized set has no get method :)

Pasted in the sun forum for the experts view

http://forums.sun.com/thread.jspa?threadID=5375529&tstart=0

Didn't get the exact answer :(

Solution: Set internally has a Map to identify and store the unique objects. In simple whatever objects we wil place in Set, it will go as a key in the internal Map with dummy optimized value.

Carefully watching the iterator implementation of Set, it is like
return map.keySet.iterator();
Seems to be pretty simple implementation.

But get method is not such simple implementation, it needs to be iterated the whole map to identify an object.

I donno how optimized it is to traverse in HashMap, TreeMap whatever map implementation has....

But still doable, I donno Why it is missing in JDK API ?