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);

}

}

}

[1983 byte] By [Mustanga] at [2007-10-3 4:10:41]
# 1
Hmm, yes, they could have declared it as:public <E extends Comparable><E>> TreeSet(Collection<E> c)
ejpa at 2007-7-14 22:11:00 > top of Java-index,Core,Core APIs...
# 2
You can pass non-Comparables to a TreeSet if you provide a Comparator. This API existed before generics and cannot be changed without breaking the existing contract.
dubwaia at 2007-7-14 22:11:00 > top of Java-index,Core,Core APIs...
# 3
But this constructor is for the case when the contents implement Comparable and no Comparator is provided.
ejpa at 2007-7-14 22:11:00 > top of Java-index,Core,Core APIs...
# 4

> But this constructor is for the case when the

> contents implement Comparable and no Comparator is

> provided.

I'll conceed that Comparator doesn't have any applicability here but they still can't change the signature that way. In the TreeSet contract, you could fill the set with items that are mutually comparable but do not have the same type. In other words, the only common subclass is Object but the items in the collection are not comparable to Object.

dubwaia at 2007-7-14 22:11:01 > top of Java-index,Core,Core APIs...
# 5
Agreed
ejpa at 2007-7-14 22:11:01 > top of Java-index,Core,Core APIs...