How come I’m allowed to do this:
TreeSet<Object> treeSet = new TreeSet<Object>();
treeSet.add(new Object());
But not this:
final List<Object> objects = new ArrayList<Object>();
Collections.sort(objects);
The first one gives me an ClassCastException but the second one gives me a compile error. As I understand it the actual problem is the same in both cases: java.lang.Object does not implement the Comparable interface.
UPDATE:
Hmm for some reason this only applies for Java 7 and not 6.
Am I being stupid or tired? Could someone please shed some light on this?
UPDATE #2:
I do get different results depending on java versions. Please see picture:

Collections.sortrequires a list ofComparable‘s.TreeSetdoesn’t have that restriction in the typing. With the default constructor, the docs say it sorts by ” natural ordering of its elements”. What isn’t clear is how it would sortObject, but your problem deals with the typing.Update:
I missed the last part of the question. Without looking at the stacktrace, I would guess that since the default constructor for
TreeSettries to sort by “natural order”, internally, it is doing a cast toComparable, which would cause aClassCastException.Update:
I looked closer at the javadocs for
TreeSet(JDK 6, JDK 7) and it saysfor both. So, if no ClassCastException happens with JDK6, perhaps it is a bug.