While I was solving a Java test I came up with the following question:
You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability?
A. java.util.Map B. java.util.Set C. java.util.List D. java.util.Collection
I have no idea what is the right case here? We can store the same element in any of these collections unless in a
Set, but the
Set doesn't provide the natural order. What's wrong?
The correct answer for that test is
Set Let's remember that it's asking for an interface that could provide that; given the right implementation, the
Set interface could provide it.
Mapinterface doesn't make any guarantees around what order things are stored, as that's implementation specific. However, if you use the right implementation (that is,
TreeMapas spelled out by the docs), then you're guaranteed a natural ordering and no duplicate entries.
However, there's no requirement about key-value pairs.
Setinterface also doesn't make any guarantees around what order things are stored in, as that's implementation specific. But, like
TreeSetis a set that can be used to store things in a natural order with no duplicates.
Here's how it'd look.
Set<String> values = new TreeSet<>();
Listinterface will definitely allow duplicates, which instantly rules it out.
Collectioninterface doesn't have anything directly implementing it, but it is the patriarch of the entire collections hierarchy. So, in theory, code like this is legal:
Collection<String> values = new TreeSet<>();
...but you'd lose information about what kind of collection it actually was, so I'd discourage its usage.