Converta uma lista genérica em uma matriz
Procurei por isso, mas infelizmente não recebo a resposta correta.
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;
}
}
Teste-o
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("abc");
String[] array = toArray(list);
System.out.println(array);
}
Mas existe um erro:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at test.Helper.main(Helper.java:30)
Como resolver isso?
ATUALIZA
Eu quero esse método, porque às vezes o tipo no meu código é muito longo:
newEntries.toArray(new IClasspathEntry[0])
Eu espero chamar:
toArray(newEntries)
FINALMENT
Parece impossível criar esse método, muito obrigado a todos!