Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeSet instance in Set reference variable

Tags:

java

set

treeset

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.

like image 246
mislav23 Avatar asked Mar 06 '19 10:03

mislav23


1 Answers

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 Sets 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);
like image 130
Andy Turner Avatar answered Sep 28 '22 10:09

Andy Turner