Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: On arraylist (unbounded wildcard type), add and addAll methods behaves differently

Tags:

java

generics

To be direct here's an example:

    ArrayList <?> x = new ArrayList();
    ArrayList y = new ArrayList();
    x.add("abc"); // Clause 1. Compilation error - No problemo. Understood.
    x.addAll(y); // Clause 2. No compilation error

For unbounded wildcard, one cannot add. Why there is no compilation error on the last statement?

like image 422
yapkm01 Avatar asked Oct 26 '11 17:10

yapkm01


1 Answers

Because you are invoking the method with a raw type. The compiler can't perform type checks. If you make y user generics, addAll(..) will fail.

like image 193
Bozho Avatar answered Oct 16 '22 16:10

Bozho