[英]misunderstanding the generic in java
I am trying to understand generics in Java. 我试图理解Java中的泛型。
private List<Own> l = new ArrayList<Own>();
I have the following error : 我有以下错误:
no instance of Typed array variable T exist so that List<Own> conform to T[]
when I pass it in a method (readTypedArray) that expects T[]. 当我在一个期望T []的方法(readTypedArray)中传递它时。
private List<Own> list = new ArrayList<Own>();
private OwnParceable(Parcel in) {
in.readTypedArray(list, CategoriesParceable.CREATOR);
}
The method in.readTypedArray()
expects an array T[]
, but you passed a List<Own
which is not an array. in.readTypedArray()
方法需要一个数组T[]
,但是你传递的是一个List<Own
,它不是一个数组。
List
is not an array
you can't use it where an array is expected, List
is an interface which extends Collection
while array
is a data structure in Java, check Difference between List and Array for further details. List
是不是一个array
,你不能用它当阵列的预期, List
是扩展的接口Collection
,而array
是Java中的数据结构,检查列表和阵列之间的差异进一步的细节。
You can either declare an Own[]
instead of List<Own>
or convert this list into an array before passing it to the method, check Convert list to array in Java : 您可以声明一个
Own[]
而不是List<Own>
或者在将该列表传递给方法之前将其转换为数组,在Java中检查将列表转换为数组 :
in.readTypedArray(list.toArray(new Own[list.size()]), CategoriesParceable.CREATOR);
This has nothing to do with generics - List
s and arrays are just two different things. 这与泛型无关 -
List
和数组只是两个不同的东西。 If your method expects an array, you need to pass it an array, not a List: 如果你的方法需要一个数组,你需要传递一个数组,而不是List:
Own[] arr = new Own[10]; // Or some size that makes sense...
in.readTypedArray(arr, CategoriesParceable.CREATOR);
There is a possibility to create an array filled with content of specified List
. 可以创建一个填充了指定
List
内容的数组。 To achieve that you can call method toArray()
of your list reference, for example: 要实现这一点,您可以调用列表引用的方法
toArray()
,例如:
Integer[] array = list.toArray(new Integer[list.size()]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.