0

Can anyone let me know why addAll method allow to compile raw type in Generic List which already has restriction of String. As per my understanding addAll(Collection< ? extends T > c) will convert to addAll(Collection < ? extends String > c) which can take String or its subtype.

    List<String> x = new ArrayList<String>();
    x.add("sfhvjk");
    //ArrayList<Integer> s = new ArrayList();
    ArrayList s = new ArrayList();

    //s.add("efyi");
    s.add(3);
    x.get(0);
    x.addAll(s);// why its not giving compile time error? 
    for( Object o :x){
        System.out.println(o);
    }
  • It's not giving an error because it's not provably unsafe; however, it should give a *warning* (unless you are suppressing it). – Andy Turner Mar 17 '17 at 09:21
  • It gives a compiler warning, furthermore if you change the for (Object o: x) to be for (String o: x) you get an Exception thrown in your face when running the program. – 7663233 Mar 17 '17 at 09:38
  • x is defined as a list of string, so each item in s will get added after a call to toString() – jr593 Mar 17 '17 at 09:38
  • Is it not that the case that List x is allowed only to have String and its subtype while calling addAll method ? – shashank shekhar Mar 17 '17 at 10:56

0 Answers0