Java_Magazine_NovemberDecember_2018

(singke) #1

85


// fi x t h i s /


second? No, it does not, because that line doesn’t
use this multiple-constraints syntax. Look
closely: it uses a comma.
That comma means that two generic vari-
ables are being declared, and the declaration is
correct, which in turn means that line 11 com-
piles, and option A is incorrect.
The first of the declared generic type variables is called T (by the way, there’s an informal
convention that T is usually short for “type” when you are using generics), and it’s constrained
to be something that implements Runnable. It’s correctly declared and constrained, which means
that the use of T as an argument in line 13 is correct, and option C is incorrect.
Also, because the type variable T carries the constraint extends Runnable, the invocation of
t.run() on line 14 is correct, and option D is incorrect.
However, in addition to declaring T with a single constraint, the comma separation in line
11 also declares another generic type variable that has a very unwise name: String. This is a
generic type variable, and it has nothing to do with java.lang.String. Because it’s not con-
strained in any way, its base representation is Object, but it’s not possible to know what type can
be assigned to it until someone makes use of the class. Imagine that the following declaration
is made:

class MyJob implements Runnable { public void run() {} }
Ex2<MyJob, LocalDate> ex2;

In this context, the type variable called String (remember—it’s not a java.lang.String) is sup-
posed to be LocalDate. It should now be clear why you cannot assign the literal java.lang.String
object Hello to it and, therefore, why line 12 fails to compile and option B is the correct answer.
Although the namespace of generic type variables is totally different from the namespace
of “real” types (classes, interfaces), ambiguities such as this one with the meaning of String
caused the adoption of the convention that type variables should generally be single uppercase

The API documentation doesn’t
always reliably tell you if a data structure
has an encounter order.
Free download pdf