robert robert - 3 months ago 5
Java Question

Java: Why can't List<Integer> be passed to function (List<Number>)?

Why can't we pass

List<X>
to a function which has
List<superclass of X>
? For a normal variable this is possible.

Consider the MWE below. Why can we pass
Integer
to a function with a
Number
argument, and can't we not pass
List<Integer>
to
List<Number>
?

Questions:


  • How can I efficiently/nicely (so without constructing a new List) work around this?

  • What is the rationale of this language design decision?



MWE:

import java.util.ArrayList;
import java.util.List;

public class Tester {
public static void main(String[] args) {
Integer i = new Integer(2);
// This works fine.
processNumber(i);
List<Integer> l = new ArrayList<Integer>();
// ERROR "The method processNumberList(List<Number>) in the type
// Tester is not applicable for the arguments (List<Integer>)"
processNumberList(l);
}
private static void processNumber(Number n) {
}
private static void processNumberList(List<Number> l) {
}
}

Answer

Replace your declaration with this:

private static void processNumberList(List<? extends Number> l) {...}