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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With