Reading and writing through bounded wildcards

A data-processing application uses this Java class. The ? in a generic type is a wildcard representing an unknown type argument.


Java
final class Cell< T > {
    private T value;

    Cell(T value) { this.value = value; }
    T get() { return value; }
    void set(T value) { this.value = value; }
}


Inside a method, the following initialized parameters are available:


Java
Cell< ? extends Number > source
Cell< ? super Integer > target


Consider each candidate statement independently. Classify it using its compile-time type, without changing the parameters or adding casts. The cast already shown in one candidate is part of that candidate.


Read candidates:


Java
Number first = source.get();
Integer second = source.get();
Object third = source.get();
Double fourth = source.get();


Write candidates:


Java
target.set(Integer.valueOf(37));
target.set(Double.valueOf(6.5));
target.set((Number) Integer.valueOf(37));
target.set(null);


Give the number of read candidates that compile and the number of write candidates that compile, each as an exact integer count of statements. Also give the most specific type guaranteed safe for assigning target.get() without a cast, choosing from Integer, Number, and Object.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Generics Questions: