Reputation: 83
For the code:
Set<Phone> set = new TreeSet<>();
set.add(new Phone("Harry"));
I get error:
Phone cannot be cast to java.base/java.lang.Comparable
Why Phone has to implement Comparable if reference variable is type Set
?
If the reference variable was TreeSet
, then of course, class Phone
must implement Comparable
.
Upvotes: 5
Views: 658
Reputation: 140318
Look at the Javadoc for TreeSet()
:
Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface.
The elements have to be somehow comparable because TreeSet
is a SortedSet
. Note that Set
s are not necessarily unordered, merely that the Set
interface does not specify the ordering. Implementing classes are allowed to define an ordering of the elements.
If you want to insert non-Comparable instances into the comparator (or use a non-natural ordering), you must invoke the constructor with an explicit comparator.
Set <Phone> set = new TreeSet<>(someComparator);
Upvotes: 4
Reputation: 49626
The actual type only matters. It's a TreeSet
, which is based on a TreeMap
, which works with Comparable
s unless another comparator is specified.
You could define a comparator based, for instance, on a Phone
property. It would obviate the need to implement Comparable
for Phone
.
Set<Phone> set = new TreeSet<>(Comparator.comparing(Phone::getModel));
Upvotes: 1
Reputation: 44952
Although the reference type is Set
, the actual implementation is still TreeSet
so TreeSet.add()
method is called. The parameter check happens in the runtime, when ThreeSet.add()
is invoked and you get an exception:
Exception in thread "main" java.lang.ClassCastException:
class java.lang.Object cannot be cast to class java.lang.Comparable
Upvotes: 1