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:
Constructs a new, empty set, sorted according to the elements' natural order. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set.
If an element is added to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add(Object) call will throw a ClassCastException; or if the to be added object cannot be compared with the elements currently in the set, the add(Object) call will throw a ClassCastException.
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.
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(15020)
- What is runtime polymorphism in Java?(9498)
- What is String literal pool?(8793)
- Can the run() method be called directly to start a thread?(8254)
- How to add BASIC Authentication into HttpURLConnection?(7483)
- Can transient variables be declared as 'final' or 'static'?(6303)
- Can static methods be overridden?(4965)
Most Recent java Faqs
- What is the difference between an enum type and java.lang.Enum?
- Which replace function works with regex?
- Why does TreeSet.add throw ClassCastException?
- What is variable hiding and shadowing?
- Can private method be overridden?
- How to enable JDBC tracing?
- How to Retrieve Automatically Generated Keys in JDBC?