List<String>[] stringList = new List<?>[10];
givesType mismatch: cannot convert from List<?>[] to List<String>[]
If i use following statement
List<? extends Number> inLi = new ArrayList<Integer>();
theninLi. inLi.add(5);
givesThe method add(int, capture#1-of ? extends Number) in the type List<capture#1-of ? extends Number> is not applicable for the arguments (int)
Asked
Active
Viewed 108 times
1

Behrang
- 46,888
- 25
- 118
- 160

Amit Kumar Gupta
- 7,193
- 12
- 64
- 90
1 Answers
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.
-
Could you plz tell alternate solution/statement for problem 1. – Amit Kumar Gupta Aug 14 '11 at 17:54
-
I am using List
[] stringList = (List – Amit Kumar Gupta Aug 15 '11 at 13:13[]) new List>[10]; for 1st problem. Whether it is good?
> stringsList = new ArrayList<>();` 2. `Lint ints = new ArrayList<>();`. Or prior to Java SE 7: 1. `List
– Tom Hawtin - tackline Aug 14 '11 at 12:04> stringsList = new ArrayList
>();` 2. `Lint ints = new ArrayList();`.