This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am preparing for OCPJP7 and for that first sitting for OCPJP6 exam. I want to know in the javadocs, it is written that TreeSet is implemented using TreeMap instance. What does it mean?
Thanks a ton for your prompt response. The confusion is, it says the TreeSet implementation is based on TreeMap. How is that?
I can see that TreeSet is composed of TreeMap. It means that, whatever the added functionality TreeMap provides like navigation
and searching is implicitly done in TreeSet via TreeMap. Am i am understanding it correct?
TreeSet data structure HAS-A TreeMap. In TreeMap, there is a key-value pair.
In TreeSet, there is a key-value pair as well. But in TreeSet, the value is always null. In TreeMap, the value is whatever value you declare.
Abhineet Kapil wrote:Array could have been used as a backing structure in a HashSet.
That's true, but then you wouldn't have O(1) access for the set.
My point is, one doesnt need K,V pair for HashSet. We only need to store values.
That's also true, but you could describe it as only storing keys. Personally I think that would be more accurate.
But I think Oracle wanted to reuse HashMap for HashSet.
That's probably true too. It's definitely a plus; the code for HashMap was already written. One other consideration is that without delegating to HashMap, the code for HashSet would have looked very much like the code for HashMap, only not quite the same. You'd have more testing to do (with delegating, a lot of your HashMap tests can work as HashSet tests as well) and you'd have duplicate maintenance to do when fixing bugs.