when I write following code I get error,
List<? extends Number> myList = new ArrayList<>();
myList.add(2);
myList.add(10);
and I know why I get error, because ? means any class that extends Number, which can be Integer, Double, ... so because the type is unspecified I can't add anything to this list. my question is what's the use case for a list which can't have an item in it? The only thing I can think of is at definition time like this :
public List<? extends Number> testMethod()
{
var x = new ArrayList<Integer>();
x.add(2);
x.add(5);
return x;
}
is that the only use case ?
and my second question is what's difference between two snippets ?
List<? super Number> myList = new ArrayList<>();
myList.add(2);
myList.add(5L);
myList.add(5.5d);
myList.add(3.2f);
System.out.println(myList);
List<Number> myList = new ArrayList<>();
myList.add(2);
myList.add(5L);
myList.add(5.5d);
myList.add(3.2f);
System.out.println(myList);