Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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: enter image description here

like image 956
Olle Söderström Avatar asked Dec 06 '22 09:12

Olle Söderström


1 Answers

Initially I frowned here, but you're right.

The SortedSet interface does not force you to specify its generic type as being Comparable as TreeSet also allows you to specify a Comparator for types that are not Comparable. The compiler can't distinguish between the two options.

like image 52
akaIDIOT Avatar answered May 22 '23 20:05

akaIDIOT