In a microservices architecture, you're designing a Response wrapper class that should work with any data type, including primitives when boxed. Which implementation is correct?
Apublic class Response { private T data; private int statusCode; }
Bpublic class Response { private Object data; private int statusCode; }
Cpublic class Response { private T data; private int statusCode; }
Dpublic class Response { private T data; private S statusCode; }
Correct Answer:
A. public class Response { private T data; private int statusCode; }
EXPLANATION
Option A provides proper generic type safety without unnecessary constraints. While Option C adds a Serializable bound (sometimes desirable), Option A is the most flexible and commonly used pattern for generic response wrappers.
A utility class needs a method that accepts a List containing elements that are instances of a specific class or its subclasses. Which wildcard notation should be used?
Apublic static void process(List
Bpublic static void process(List list)
Cpublic static void process(List
Dpublic static void process(List list)
Correct Answer:
A. public static void process(List
EXPLANATION
'? extends TargetClass' creates a covariant wildcard allowing lists of TargetClass or any subclass. This is ideal for reading operations when you need polymorphic list handling.
A developer creates a generic method that accepts a collection of numbers and calculates their sum. Which type parameter declaration would be most appropriate for this scenario?
Apublic static double calculateSum(List numbers)
Bpublic static double calculateSum(List numbers)
Cpublic static double calculateSum(List numbers)
Dpublic static double calculateSum(List numbers)
Correct Answer:
A. public static double calculateSum(List numbers)
EXPLANATION
Using 'T extends Number' establishes an upper bound, allowing the method to work with any Number subclass (Integer, Double, Float, etc.) while providing type safety and access to Number methods.
Consider the code:
java
List list = new ArrayList();
Will this compile?
AYes, Integer is a subtype of Number
BNo, ArrayList is not compatible with List
CYes, with warning
DDepends on compiler version
Correct Answer:
B. No, ArrayList is not compatible with List
EXPLANATION
Generics are invariant. ArrayList<Integer> cannot be assigned to List<Number> even though Integer is a subtype of Number. This prevents type safety issues.