mislav23
mislav23

Reputation: 83

TreeSet instance in Set reference variable

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

Answers (3)

Andy Turner
Andy Turner

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 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);

Upvotes: 4

Andrew
Andrew

Reputation: 49626

The actual type only matters. It's a TreeSet, which is based on a TreeMap, which works with Comparables 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

Karol Dowbecki
Karol Dowbecki

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

Related Questions