0

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 saying that

ArrayList<? extends Number> numberList = new ArrayList<Number>();
    numberList = new ArrayList<Integer>();
    numberList.add(100);

The method add(int, capture#2-of ?) in the type ArrayList<capture#2-of ?> is not applicable for the arguments (int).

I have tried with this way also, but is giving me the same error

ArrayList<?> numberList = new ArrayList<Number>();
    numberList = new ArrayList<Integer>();
    numberList.add(100);

The error is :

The method add(int, capture#2-of ?) in the type ArrayList<capture#2-of ?> is not applicable for the arguments (int)

halfer
  • 19,824
  • 17
  • 99
  • 186
zameer
  • 471
  • 1
  • 5
  • 15
  • 3
    Check http://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super . You can't add anything to a Collection that has `? extends ` – TheLostMind Aug 08 '16 at 11:31

5 Answers5

2

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
2

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);
Héctor
  • 24,444
  • 35
  • 132
  • 243
1

you can use;

 ArrayList <?  super Number> numberList = new ArrayList<Number>();
 Number number = 1;
 numberList.add(number);

 or

 numberList.add(1);
Sinan
  • 21
  • 2
1

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);
Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45
0

A possible workaround:

List<? extends Number> numberList = new ArrayList<Number>();
List<Integer> integerList = new ArrayList<>():
integerList.add(100);
numberList = integerList;
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93