Why can't I add a String to a type in List <?>?
Error:
The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (String) Code:
List<?> to = new ArrayList<Object>(); to.add(new String("here")); Since List<?> Is a generic type of List and therefore can be of any type, why doesn't it accept String in the add method?
+6
5 answers
A List<?> Is a list of some type that is unknown. Thus, you cannot add anything to it except zero, without violating the list type security:
List<Integer> intList = new ArrayList<>(); List<?> unknownTypeList = intList; unknownTypeList.add("hello"); // doesn't compile, now you should see why +11