TreeSet throws ClassCastException
when u pass a collection to a TreeSet constructor it accepts it but throws ClassCastException(coz it expects the elements to be comparables), instead if we can restrict that the collection should be a collection of comparables then we won't be getting this ClassCastException and infact the TreeSet expects a collection of Comparables but it does't restrict from passing an a collection of non-comparables. Then why did the developers of TreeSet leave out this is this intentionally done or by mistake..? just want to know...
my suggestion is to have something like this
(a)
public TreeSet<E extends Comparable><E>>
instead of
(b)
public TreeSet<E>
Comments are welcome...
Thanks
The below code is an example to reproduce the above ....
import java.util.*;
class Color {
private String color;
public static Color RED = new Color("RED");
public static Color BLUE = new Color("BLUE");
public static Color GREEN = new Color("GREEN");
public static Color red = new Color("RED");
private Color(String c) {
this.color = c;
}
public boolean equals(Object o) {
if(!(o instanceof Color)) return false;
Color c = (Color) o;
return this.color.equals(c.color);
}
public String toString(){
return color;
}
public int hashCode(){
return color.hashCode();
}
}
public class SetDemo {
public static void main(String ... args) {
ArrayList<Color> clist = new ArrayList<Color>();
clist.add(Color.RED);
clist.add(Color.RED);
clist.add(Color.RED);
clist.add(Color.BLUE);
clist.add(Color.BLUE);
clist.add(Color.GREEN);
clist.add(Color.red);
Set<Color> set = new TreeSet<Color>(clist); // here i get classcast exception.
for(Color c : set) {
System.out.println(c);
}
}
}

