0

Java has List.toArray() to convert a list to Object[]. I want to convert a list of A to an array of A rather than Object. This is my code:

public static <A> A[] toArray(List<A> list) {
    A[] rtn = null;
    if (list != null) {
        int mi = list.size();
        rtn = new A[mi];//Error: Cannot create a generic array of A
        for (int i = 0; i < mi; i++) {
            rtn[i] = list.get(i);
        }
    }
    return rtn;
}

However the line with note causes an error: Cannot create a generic array of A.

How can I bypass this?

Changwang Zhang
  • 2,309
  • 3
  • 30
  • 53

2 Answers2

2

it's not easy, this should work

@SuppressWarnings("unchecked")
public static <A> A[] toArray(List<A> list, Class<A> cls) {
    return list.toArray((A[]) Array.newInstance(cls, list.size()));
}
Evgeniy Dorofeev
  • 124,221
  • 27
  • 187
  • 258
-1

convert it to an Arraylist and then use the overridden toArray() method

Arraylist<String> newList = new Arraylist(yourStringList);
String [] stringArray = new String[newList.size()];
stringArray = newList.toArray();
shazinltc
  • 3,406
  • 7
  • 29
  • 47
  • You could do `newList.toArray(stringArray);`, but I guess the question anyhow aimed at the cases where you don't know the type (like `String` in your example) – Marco13 Apr 03 '14 at 10:58
  • "Conversion" to `java.util.ArrayList` doesn't change anything. – greybeard Oct 10 '17 at 18:39