Question:
Suppose we have a parametrized class
public class Example<X> {
...
}
What can be substituted as the value of the X parameter when using this class in a program?
-
the name of any interface (for example, CharSequence)
-
symbol "?" or a more complex expression with the extends and super keywords
- the value of X can be omitted, i.e. use the Example class as a regular non-parameterized
- the name of any class (for example, Object)
-
the name of any primitive type (for example, int)
-
method reference (for example, Object::toString)
- the name of any enum (for example, DayOfWeek)
- primitive type value (for example, 42)
Please explain why answers 1, 2, 3, 4 do not fit?
Answer:
Type arguments in Java are defined in the specification in p.p. 4.5.1 .
As an argument, according to the specification, you can put a reference type ( ReferenceType
in Java is any non-primitive type) or a mask ( WildCard
, i.e. the expression ? extends/super T
).
Here is an example of a valid use of Example
:
Example<CharSequence> a = new Example<CharSequence>();
Example<?> b = new Example<Object>();
Example<? extends List> c = new Example<List>();
Example d = new Example();
Example<Object> e = new Example<Object>();