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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With