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
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.