Convert a generic list to an array

Posted by Freewind on Stack Overflow See other posts from Stack Overflow or by Freewind
Published on 2011-06-29T14:24:22Z Indexed on 2011/06/29 16:22 UTC
Read the original article Hit count: 336

Filed under:
|

I have searched for this, but unfortunately, I don't get the correct answer.

class Helper {
    public static <T> T[] toArray(List<T> list) {
        T[] array = (T[]) new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }
}

Test it:

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("abc");
    String[] array = toArray(list);
    System.out.println(array);
}

But there is an error thrown:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at test.Helper.main(Helper.java:30)

How to solve this?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics