I have searched for this, but unfortunately, I don\'t get the correct answer.
class Helper {
public static T[] toArray(List list) {
The problem is the component type of the array that is not String.
Also, it would be better to not provide an empty array such as new IClasspathEntry[0]. I think it is better to gives an array with the correct length (otherwise a new one will be created by List#toArray which is a waste of performance).
Because of type erasure, a solution is to give the component type of the array.
Example:
public static C[] toArray(Class componentType, List list) {
@SuppressWarnings("unchecked")
C[] array = (C[])Array.newInstance(componentType, list.size());
return list.toArray(array);
}
The type C in this implementation is to allow creation of an array with a component type that is a super type of the list element types.
Usage:
public static void main(String[] args) {
List list = new ArrayList();
list.add("abc");
// String[] array = list.toArray(new String[list.size()]); // Usual version
String[] array = toArray(String.class, list); // Short version
System.out.println(array);
CharSequence[] seqArray = toArray(CharSequence.class, list);
System.out.println(seqArray);
Integer[] seqArray = toArray(Integer.class, list); // DO NOT COMPILE, NICE !
}
Waiting for reified generics..