File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Generics: TreeSet where class parameter does not implement Comparable... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics: TreeSet where class parameter does not implement Comparable..." Watch "Generics: TreeSet where class parameter does not implement Comparable..." New topic
Author

Generics: TreeSet where class parameter does not implement Comparable...

Glen Kidston
Greenhorn

Joined: Feb 26, 2005
Posts: 9
I think I understand why the following code:

results in:

Ah hah, thought so.
java.lang.ClassCastException: Car
at java.util.TreeMap.compare(TreeMap.java:1093)
at java.util.TreeMap.put(TreeMap.java:465)
at java.util.TreeSet.add(TreeSet.java:210)
at DriveCar.main(DriveCar.java:13)

This error is due to the fact that Car does not "implement Comparable", and the TreeSet<Car>() as constructed with the default constructor depends on the "natural order" of Car and the ClassCastException happens when the attempt is made to add c2 to the TreeSet and it tries to compare c2 to c1.

Getting to my question (thank you very much for reading this far)... So my question is why didn't the Java language developers create some way of declaring the constructor so we could prevent this runtime exception? This implicit "natural ordering" restriction seems like kind of a subtle and tricky problem to stay on top of.

I would have liked to see some new Generics augmented type safe Constructor declaration syntax. I don't know what, but maybe instead of:

Maybe something like:

I don't know if I'm even making any sense--I guess that's the 2nd part of this question. Does this even make any sense? Thanks to any and all for reading.
-Glen
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
My guess is that TreeSet can also work with non-Comparable objects if you pass in a Comparator to the constructor. However, since the <E> applies to the entire TreeSet, regardless of which constructor is called, it wouldn't be possible to specify <E extends Comparable>. Do note that Java does allow this construct and uses it where appropriate in other classes.

I suppose it would have been possible to create two TreeSet implementations, but that would have broken backwards compatibility, the bane of all framework developers.
Glen Kidston
Greenhorn

Joined: Feb 26, 2005
Posts: 9
David,
Thank you very much!
-Glen
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics: TreeSet where class parameter does not implement Comparable...