将通用列表转换为数组 [英] Convert a generic list to an array
问题描述
类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);
}
返回数组;
$ / code>
测试:
public static void main(String [] args){
List< String> list = new ArrayList< String>();
list.add(abc);
String [] array = toArray(list);
System.out.println(array);
}
但引发错误:
线程main中的异常java.lang.ClassCastException:[Ljava.lang.Object;不能转换为[Ljava.lang.String;
at test.Helper.main(Helper.java:30)
如何解决这个问题?
$ b
更新
我想要这个方法,因为有时候,我的代码中的类型太长了:
$ b $ $ p $ newEntries.toArray(new IClasspathEntry [0] )
我希望打电话:
toArray(newEntries)
FINALLY
似乎不可能创建这样一种方法,非常感谢大家!
您可以直接致电 list.toArray(T [] array)
并且不必担心关于自己实现它,但正如aioobe所说,由于类型擦除,您不能创建一个泛型类型的数组。如果您需要返回该类型,则需要自己创建一个类型化实例并将其传入。
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?
UPDATE
I want this method, because sometimes, the type in my code is too long:
newEntries.toArray(new IClasspathEntry[0])
I'd hope to call:
toArray(newEntries)
FINALLY
It seems impossible to create such a method, thank you all very much!
You can just call list.toArray(T[] array)
and not have to worry about implementing it yourself, but as aioobe said, you can't create an array of a generic type due to type erasure. If you need that type back, you need to create a typed instance yourself and pass it in.
这篇关于将通用列表转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!