Reputation: 687
Constructor for any Collection :
public TreeSet(Collection<? extends E> c)
Seperate constructor for SortedSet :
public TreeSet(SortedSet<E> s)
Why there is a need for a separate one for SortedSet?
Upvotes: 1
Views: 498
Reputation: 788
Let's run this program with two different flavors,
public static void main(String[] args) {
List<User> ul = new ArrayList<>();
ul.add(new User());
ul.add(new User());
Set<User> users = new TreeSet<>(ul);
}
first with below (here we are implementing Comparator)
private static class User implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
return 0;
}
}
With this program, it throws Exception in thread "main" java.lang.ClassCastException: test.WTest$User cannot be cast to java.lang.Comparable
Because this constructor expects the User to be implementing java.util.Comparable interface.
Second run, if you change the User class implementation to below
private static class User implements Comparable<User> {
@Override
public int compareTo(User o) {
return 0;
}
}
The code runs just fine! Notice the difference in the implements, now we are implementing java.lang.Comparable interface.
But TreeSet class works with both, either with Comparator or Comparable. So the choice of the constructor purely depends on the type of implementation your object has.
Upvotes: 1
Reputation: 1148
public TreeSet(Collection<? extends E> c)
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.
Pay more attention at "sorted according to the natural ordering of its elements"
public TreeSet(SortedSet<E> s)
Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.
Upvotes: 1
Reputation: 29700
From the documentation of the constructor that accepts a SortedSet
:
Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.
When initializing a TreeSet
from a Collection
, the natural ordering of the elements is used, as seen from the documentation of the other constructor that accepts a Collection
:
Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
Upvotes: 2