I have a ArrayList generic wildcards type, which is taking Number as extends. I am trying to add the integer values to the ArrayList.
Buts it\'s giving me an error
You Should do something like this
ArrayList<? super Number> numberList = new ArrayList<Number>();
numberList.add(100);
for java 8, you can use stream(),
// to resolve your read problem cause by <? super>
ArrayList<? super Number> arrayList = new ArrayList<Number>();
arrayList.add(100);
List<Integer> list = arrayList.stream().map(e->(Integer) e).collect(Collectors.toList());
System.out.println(list);
you can use;
ArrayList <? super Number> numberList = new ArrayList<Number>();
Number number = 1;
numberList.add(number);
or
numberList.add(1);
You can't add a Integer to the list because maybe it is a list of Float, and not a list of Integer.
You can do:
ArrayList<? super Number> numberList = new ArrayList();
numberList.add(100);
or just
ArrayList<Number> numberList = new ArrayList();
numberList.add(100);
A possible workaround:
List<? extends Number> numberList = new ArrayList<Number>();
List<Integer> integerList = new ArrayList<>():
integerList.add(100);
numberList = integerList;
You can't. the ? extends
part basically tells the compiler: it is of some type, which I don't know, but which extends Number.
So the compiler can't guarantee that the type of whatever you want to add is compatible to the unknown type. Therefor you can't add anything to such a collection.