Yeah, that's nasty, but none of that is caused by the actual autoboxing. (You get the same error if you replace 1337 with new Integer(1337), where you do the boxing yourself.)
Two things are happening in your code, both of them related to this "cast-up" effect of the ternary operator (the question-mark (?) operator thing).
I earlier said that if you try to do A? B : C, then it looks for the lowest mutual superclass it can do. That's only a part of the truth -- it then *extends* this superclass, with a derived one that implements any mutual interfaces that both subclasses have, but the superclass does not.
When you try to use a ternary operator on an Integer and a String, instead of just getting an Object, you get a:
- Code: Select all
? extends java.lang.Object
&java.io.Serializable
&java.lang.Comparable<
? extends java.lang.Object
&java.io.Serializable
&java.lang.Comparable<?>>
Now, one of the things that's killing your code is just the redundancy of the generic in the Comparable class. The object that the ternary operator creates is, as far as I can tell, only Comparable to itself -- you cannot, as far as I know, create *any* another object of the same anonymous class to compare it with. And so the above specification states that outright. It just means many more characters to deal with.
Okay, so let's replace that whole long "? extends Object" thing in the code block, above, with the letter A. If we call this anonymous class A, what's happening in your particular compiler error?
Well, first off, the LinkedList doesn't get cast to a different class. It doesn't need to be; both objects are LinkedLists. So their superclass is a LinkedList, too.
But aha, these aren't *quite* the same class. One is a subclass called LinkedList<Integer> and the other is a subclass called LinkedList<String>. And, though you don't need to send the LinkedList to a superclass, you do need to send the generics there. So we're casting to a LinkedList<A>.
And that's not quite enough, either. LinkedList<String> also implemented some of its interfaces with generics -- for example, it implements Iterable<String>. Any genericized interfaces *also* need to be respecified.
If I just rewrite your error message with my A convention, and with some whitespace tossed in, it says:
- Code: Select all
print(java.util.LinkedList<java.lang.String>) in Test cannot be applied to (
java.util.LinkedList<A>
&java.util.AbstractSequentialList<A>
&java.util.AbstractList<A>
&java.util.List<A>
&java.util.AbstractCollection<A>
&java.util.Queue<A>
&java.util.Collection<A>
&java.lang.Iterable<A>)
So, all of the genericized LinkedList interfaces also got respecified.
And that's how your compiler message from hell was created -- generics + ternary operators + two classes which were both Comparable and Serializable, but could not be traced to a superclass.