To store a single item in a collection with a natural order

advertisements

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.

  • The Map interface 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, TreeMap as 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.

  • The Set interface also doesn't make any guarantees around what order things are stored in, as that's implementation specific. But, like TreeMap, TreeSet is 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<>();
    
    
  • The List interface will definitely allow duplicates, which instantly rules it out.

  • The Collection interface 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.