Can someone explain the following behavior to me?
I have a list of X
and use the addAll()
method to add elements. These elements are returned by a method using generic types. Method getA()
returns < T extends A >
with A
being a class. Method getI()
returns < T extends I >
with I
being an interface (see code below).
Difference: with listX.addAll(getA())
I get a compile error (as expected), but listX.addAll(getI())
compiles (throws a runtime error when element is cast to X
).
Simpified code:
interface I {}
class A implements I {}
class X {}
public void test() {
List<X> listX = new ArrayList<>();
listX.addAll(getA());
listX.addAll(getI());
for (X x : listX) {}
}
public <T extends A> List<T> getA() {
return new ArrayList<>();
}
public <T extends I> List<T> getI() {
return new ArrayList<>();
}
Am I missing something? Shouldn't I get a compile error both times?
That behavior seems to be new with Java 8, with versions below I have gotten compiler errors in both cases.