04: 5 Java generics Interview Q&As on wildcards with examples

Q1. If java.lang.Object is the super type for java.lang.Number and, Number is the super type for java.lang.Integer, am I correct in saying that List<Object> is the super type for List<number> and, List<Number> is the super type for List<Integer>.

A1. No. List<Object> is not the the super type of List<Number>. If that were the case, then you could add objects of any type, and it defeats the purpose of Generics.

In Generics, wildcards (i.e. ?), makes it possible to work with super classes and sub classes.

Q2. How will you go about deciding which of the following to use?

  • <Number>
  • <? extends Number>
  • <? super Number>

A2. Here is the guide:

1. Use the ? extends wildcard if you need to retrieve object from a data structure. That is read only. You can’t add elements to the collection.
2. Use the ? super wildcard if you need to put objects in a data structure.
3. If you need to do both things (read and add elements), don’t use any wildcard.

Scenario 1: A custom generic class GenericSingleTypeScenario class that handles a given input of type T, where “T” can be any type.

Add a test class with a main method to test the above class with “T” being an “Integer”

Output:

Scenario 2: It can handle any given input of type Number like Integer, Long, and Double.

Output:

Scenario 3: “T” being a “String”.

Output:

Scenario 4: “T” being any “Object”

Output:

Why use wildcards?

Q3. Why was the read(….) method in “GenericSingleTypeScenario.java” was implemented with wildcard “? extends T” as opposed to just “T” as shown below:

A3. The reason being what if you want to read a List<Double> from that method. If you were to NOT use the wildcard as in “? extends T the following code would have a compile error.

This is the reason why “? extends T” was introduced to be able to read List<Integer>, List<Double>, List<Long>, etc in a generic manner.

Q4. What if you use just use “?” instead of “? extends T”?
A4. The above code would compile, but the read(…) method must be changed to use “Object” as shown below as it could take a List<String> as well.

and the following code will compile.

Q5. Where will you apply the wild card “? super T“?
A5. If you were to add the following method to “GenericSingleTypeScenario.java”

The following code will compile.

Output:

The following code without the wildcard “? super T”

will throw a compile error as shown below as “T” is an “Integer” and List<Number> cannot be assigned to add(…..) method’s first argument List<Integer>

But it will be able to assigned to List<? super Integer> as “Number” is a super class of “Integer”.


300+ Java Developer Interview Q&As

800+ Java Interview Q&As

Top