开发者

Generics: suggest correct syntax

  1. List<String>[]开发者_如何学C 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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜