| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Why does TreeSet.add throw ClassCastException?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Why does TreeSet.add throw ClassCastException?The following code throws ClassCastException, why?
class MyObject {
int i;
MyObject(int i) {
this.i = i;
}
}
public class Program {
public static void main(String[] args) {
Set s = new TreeSet();
s.add(new MyObject(1));
s.add(new MyObject(2)); //Runtime exception: ClassCastException
....
}
}
The TreeSet() Constructor said:
In the above code, the MyObject class does not implement the Comparable interface. Therefore, when the second object is added to the TreeSet, the second object can't be compared with the first element already in the set, the code throws a ClassCastException. |