3

I am trying to understand generics in 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[].

private List<Own> list = new ArrayList<Own>();

private OwnParceable(Parcel in) {
    in.readTypedArray(list, CategoriesParceable.CREATOR);
}
cнŝdk
  • 28,676
  • 7
  • 47
  • 67

3 Answers3

3

The method in.readTypedArray() expects an array T[], but you passed a List<Own which is not an array.

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.

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:

in.readTypedArray(list.toArray(new Own[list.size()]), CategoriesParceable.CREATOR);
cнŝdk
  • 28,676
  • 7
  • 47
  • 67
1

This has nothing to do with generics - Lists and arrays are just two different things. If your method expects an array, you need to pass it an array, not a List:

Own[] arr = new Own[10]; // Or some size that makes sense...
in.readTypedArray(arr, CategoriesParceable.CREATOR);
Mureinik
  • 252,575
  • 45
  • 248
  • 283
0

There is a possibility to create an array filled with content of specified List. To achieve that you can call method toArray() of your list reference, for example:

Integer[] array = list.toArray(new Integer[list.size()]);
Przemysław Moskal
  • 3,321
  • 2
  • 8
  • 20