Ok so SortedMap / SortedSet is an interface, and TreeMap / TreeSet is it’s implementation. Both of them keep the elements in sorted order, right? So why do we need TreeMap / TreeSet?
Ok so SortedMap / SortedSet is an interface, and TreeMap / TreeSet is it’s
Share
Interfaces do not provide any functionality, they just define the general outline of a class in terms of the methods it provides. But there’s no code inside
SortedMap/SortedSetthat implements how to actually achieve this functionality.And as a matter of fact, you can often have multiple ways to realize the same functionality. Think of the interface
java.util.Set: you could implement it as aTreeSetbut also as aHashSet. Usually, there are some trade-offs between different implementations: a hashset might provide faster access times on average, while a tree set may be better at keeping the order of its items.Often enough, however, a developer doesn’t really care about the implementation details, as long as they know that they can store items in a set and retrieve them. That basic idea, but not how to achieve it, is defined by the interface.
This is also the reason you cannot instantiate an interface. If you try the following:
your compiler will complain. That is because “SortedSet” does not really realize a set itself, it just defines what an implementation of a sorted set must provide in terms of methods.
Here’s a contrived example. Imagine you want to offer a functionality to compute the percentage of positive integers in a set. You could define a method:
Here, you don’t really care whether the user of your method gives you a
TreeSetor aHashSet. It doesn’t matter which principle the given class uses, because you’re just calling thesize()method and theiterator()method anyway. All you need is trust in the fact that any set will have these two methods. An interface gives you that trust.Therefore your method signature only asks for a
Set, which is an interface that defines that all classes implementing it must provide (amongst others) asize()and aniterator()method. If you wrote it like this:and I have an instance of
HashSetthen I couldn’t use your method even thoughHashSetprovidessize()anditerator()as well. 🙁In that sense, an interface is like a super-class, it defines the commonalities that all classes must have that implement it. But it does not provide any functionality itself.
Thus to come back to your original example of
SortedSet: this interface does not provide any functionality. It merely defines which methods a sorted set implementation must provide.TreeSetis such an implementation.The same line of thought applies to
SortedMap.