1
  1. List<String>[] stringList = new List<?>[10]; gives Type mismatch: cannot convert from List<?>[] to List<String>[]

  2. If i use following statement List<? extends Number> inLi = new ArrayList<Integer>(); then inLi. inLi.add(5); gives The method add(int, capture#1-of ? extends Number) in the type List<capture#1-of ? extends Number> is not applicable for the arguments (int)

Behrang
  • 46,888
  • 25
  • 118
  • 160
Amit Kumar Gupta
  • 7,193
  • 12
  • 64
  • 90
  • 1. `List> stringsList = new ArrayList<>();` 2. `Lint ints = new ArrayList<>();`. Or prior to Java SE 7: 1. `List> stringsList = new ArrayList>();` 2. `Lint ints = new ArrayList();`. – Tom Hawtin - tackline Aug 14 '11 at 12:04

1 Answers1

5

No. 1 doesn't work, because List<String>[] means an array of String lists, while List<?>[] means an array of lists of anything. In a List<String>[] array, you can not have a List<Integer> element, but List<?>[] could have an element that's a List<Integer>, hence the type mismatch error.

In short, in Java it is not possible to create a generic array like this:

Foo<T>[] fooArray = new Foo<T>[];

But you can create a generic array like this:

@SuppressWarnings("unchecked") // optional but informs the compiler 
                               // not to generate warning message
List<String>[] stringList = new ArrayList[10];

For more information see this.

Regarding 2, see this.

Community
  • 1
  • 1
Behrang
  • 46,888
  • 25
  • 118
  • 160