Michael
Michael

Reputation: 33297

ClassCastException when inserting into a TreeSet

Having the following Java TreeSet

TreeSet<Widget> tabs = new TreeSet<Widget>();

When I do tabs.add(new Widget());in method a() it worked. When I do the same in method b() shortly after the first insert is performed I the a ClassCastException.

Change

ArrayList<Widget> tabs = new ArrayList<Widget>();

It works fine in both methods a() and b() without any error. I was wondering why there is a ClassCastException in the first example. There is no casting in place.

Edit: Here are method a, b and the Widget class:

 private void a() {
   tabs.add(new Widget());
 }

 private void b() {
   tabs.add(new Widget());
 }

public class Widget() {}

How do I make the first example to work?

Upvotes: 1

Views: 53

Answers (1)

Todd
Todd

Reputation: 31710

When you add to a TreeSet, the object you pass must either implement Comparable or you must specify a Comparator at the time the TreeSet is constructed.

From the JavaDoc:

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

And the JavaDoc for TreeSet.add(E) even tells you why this happens...

ClassCastException - if the specified object cannot be compared with the elements currently in this set

Upvotes: 4

Related Questions