Creating generic arrays in Java
public K[] toArray()
{
K[] result = (K[])new Object[this.size()开发者_如何转开发];
int index = 0;
for(K k : this)
result[index++] = k;
return result;
}
This code does not seem to work, it will throw out an exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to ...
Could someone tell me how I can create an array with a generic type? Thanks.
You can't: you must pass the class as an argument:
public <K> K[] toArray(Class<K> clazz)
{
K[] result = (K[])Array.newInstance(clazz,this.size());
int index = 0;
for(K k : this)
result[index++] = k;
return result;
}
Ok, this not works K[] result = new K[this.size()];
If you could hold class. Then:
Class claz;
Test(Class m) {
claz = m;
}
<K> K[] toArray() {
K[] array=(K[])Array.newInstance(claz,this.size());
return array;
}
Your code throws that exception because it's actually giving you an array of type Object
. Maurice Perry's code works, but the cast to K[ ]
will result in a warning, as the compiler can't guarantee type safety in that case due to type erasure. You can, however, do the following.
import java.util.ArrayList;
import java.lang.reflect.Array;
public class ExtremeCoder<K> extends ArrayList<K>
{
public K[ ] toArray(Class<K[ ]> clazz)
{
K[ ] result = clazz.cast(Array.newInstance(clazz.getComponentType( ), this.size( )));
int index = 0;
for(K k : this)
result[index++] = k;
return result;
}
}
This will give you an array of the type you want with guaranteed type safety. How this works is explained in depth in my answer to a similar question from a while back.
精彩评论