How come I get compile time error when use Collections.sort() but not with TreeSet.add(new Object())

java

Solution

`Collections.sort` requires a list of `Comparable`'s. `TreeSet` doesn'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 sort `Object`, 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 `TreeSet` tries to sort by "natural order", internally, it is doing a cast to `Comparable`, which would cause a `ClassCastException`.

Update: I looked closer at the javadocs for `TreeSet` (JDK 6, JDK 7) and it says

Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add call will throw a ClassCastException.

for both. So, if no ClassCastException happens with JDK6, perhaps it is a bug.

Problem

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:

Original source