java – What can be substituted as the value of the X parameter when using this class in a program?

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?

  1. the name of any interface (for example, CharSequence)

  2. symbol "?" or a more complex expression with the extends and super keywords

  3. the value of X can be omitted, i.e. use the Example class as a regular non-parameterized
  4. the name of any class (for example, Object)
  5. the name of any primitive type (for example, int)

  6. method reference (for example, Object::toString)

  7. the name of any enum (for example, DayOfWeek)
  8. 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>();
Scroll to Top