0

Why the last line does not work where as objectList.add("test"); works fine.

    List<String> stringList = new ArrayList<>();
    List<Object> objectList = new ArrayList<>();

    objectList.add("test");
    stringList.add("test");
    objectList = stringList; //Type mismatch: cannot convert from List<String> to List<Object>
Jigar Naik
  • 1,946
  • 5
  • 29
  • 60
  • In order to stop the next line being `objectList.add(new Object());`. If your assignment worked, `stringList` would then contain something that is not a String. – Andy Turner May 07 '19 at 04:34
  • You can add only Strings to `List` whereas you can add any object to `List`. This post has a good explanation https://stackoverflow.com/questions/12972910/why-and-what-of-polymorphic-generic-types/12973616#12973616 – BlackPearl May 07 '19 at 04:35

0 Answers0