I try to understand how is it possible to have a Double value into an ArrayList of Integer. The numList is an ArrayList of Integer, and the value from it is a Double.
This is the code:
package bounded.wildcards;
import java.util.ArrayList;
import java.util.List;
public class GenericsDemo {
public static void main(String[] args) {
// Invariance Workaround
List<Integer> numList = new ArrayList<>();
GenericsDemo.invarianceWorkaround(numList);
System.out.println(numList);
}
static <T extends Number> void invarianceWorkaround(List<T> list) {
T element = (T) new Double(23.3);
list.add(element);
}
}
This will compile and run without an error.
ArrayList<Double>at runtime... because the answer is because of type erasure. As such, it follows you must either not know about type erasure mechanism in Java or not understand it, which both mean you should learn more about it.