Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection to typed array

If I have a Collection defined as Collection collection = new ArrayList() which contains String instances, how can I convert it to a String[]? collection.toArray() returns an Object[]. Alternatively, how can I instantiate an ArrayList<String> using reflection?

Note that I cannot hardcode String, the method doing this only knows about the Class that it can work with.

Example:

Object test(Class classToCastTo, Object[] values) {
    Collection collection = new ArrayList();
    for (Object value : values) {
        collection.add(classToCastTo.cast(value));
    }
    return collection.toArray();
}

If I call this with test(String.class, ...), then it will return an Object[]. How can I make it return a String[]?

like image 798
rid Avatar asked May 11 '26 23:05

rid


1 Answers

Use theCollection.toArray((T[])java.lang.reflect.Array.newInstance(theClass, theCollection.size())), where T is the element type. The cast is safe as long as T is an unparameterized type.

like image 119
Ben Schulz Avatar answered May 13 '26 12:05

Ben Schulz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!