Generics: suggest correct syntax
List<String>[]开发者_如何学C 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)
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.
加载中,请稍侯......
精彩评论