Gerardo Zinno Gerardo Zinno - 20 days ago 7
Java Question

How does TreeSet<E> keep the elements sorted and avoid inserting duplicates if not specified <E extends Comparable<E>>?

How can a

TreeSet<E>
(and any other class/ interface) keep elements ordered/sorted and avoid inserting duplicates if not specified
<E extends Comparable<E>>
?

And why it is not specified that E should be "Comparable"?

Is there any difference between :

public class A<E extends Comparable<E>> {
.
.
.
SortedSet<E> elem = new TreeSet<E>();

}


and

public class A<E> {
.
.
.
SortedSet<E> elem = new TreeSet<E>();
}


What if I use only the methods that the
SortedSet
interface provides me to work with the elements of type
E
?

Answer

Read the Javadoc of the no-comparator constructors:

Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set.

The point is that you can construct a TreeSet of non-Comparable elements, by providing a Comparator, so the class can't generally be constrained such that E extends Comparable<E>.