Diagnostic Quiz

Problems

For questions 4, 5, 7, 8, 11, we are given three classes, Gala, Apple, and Fruit, with Gala <: Apple <: Fruit, along with the class Seq<T> that we have developed in the lecture and notes.

04. CTT with Producer using upper-bounded wildcard

seq.get(0) may produce any type which is the subtype of Apple. So, to ensure the code compiles, the CTT to item must be any supertype of Apple (including Apple). Thus, the correct options are:

  1. Apple

  2. Fruit

  3. Object

05. CTT with Consumer using upper-bounded wildcard

seq.set(0, item) needs the type of item to be the subtype of type of the element in the seq, which must be any subtype of Apple. Since the type of the element is not decided during the compile-time, we can only put null into seq! Tricky ah 😰

07. CTT with Producer using lower-bounded wildcard

Similar analysis as in 04. CTT with Producer using upper-bounded wildcard, here seq.get(0) will return the type that is any supertype of Apple and for this code to be compilable, the type of item can only be Object!

08. CTT with Consumer using lower-bounded wildcard

Similar analysis to 05. CTT with Consumer using upper-bounded wildcard, here the seq.set(0, item) requires the type of item to be the subtype of the type of each element in seq. Since the type of each element in seq is of any supertype of Apple, thus the available type options for item here should be:

  1. Gala

  2. Apple

11. CTT with Consumer using unbounded wildcard

Similar analysis to 07. CTT with Producer using lower-bounded wildcard, here the type of item must be subtype of each element in the seq. Since the type of each element in seq is unknown during the compile time, thus only null can be put into seq!

13. Type Inference

For this question, consider this background

along with the Seq<T> class we developed in the lecture/notes.

When we can do type inference, this means that the code can compile!

  • Wildcard bound: ? super T (the wildcard must be a supertype of T).

  • Argument passed: Seq<G>.

  • Inference: To satisfy ? super T, G must be a supertype of TT <: G (T is bounded above by G).

Tips

  1. Type Inference on wildcards when we pass arguments:

    • ? super T (Lower-bounded wildcards) → Argument type sets an upper bound for T (T is a subtype of the argument type).

    • ? extends T (Upper-bounded wildcards) → Argument type sets a lower bound for T (T is a supertype of the argument type).

Last updated