Java Programming - Objects and Collections - Discussion

4. 

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

Answer: Option B

Explanation:

Option B is correct. A set is a collection that contains no duplicate elements. The iterator returns the elements in no particular order (unless this set is an instance of some class that provides a guarantee). A map cannot contain duplicate keys but it may contain duplicate values. List and Collection allow duplicate elements.

Option A is wrong. A map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order (ascending key order); others, like the HashMap class, do not (does not guarantee that the order will remain constant over time).

Option C is wrong. A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

Option D is wrong. A collection is also known as a sequence. The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.


Marco S said: (Nov 21, 2013)  
A *Set* is not guaranteed to keep natural ordering (see HashSet). The correct answer should be java.util.SortedSet.

Ormek said: (Mar 17, 2018)  
What does "natural order" mean?

Coddi said: (Sep 3, 2018)  
Natural ordering is basically the way Java sorts data by default.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.