--
The following code throws ClassCastException, why?
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.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.
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.
Comments
Post a Comment