Creating generic arrays in Java

折月煮酒 提交于 2020-02-11 08:55:07

问题


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.


回答1:


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;
}



回答2:


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.




回答3:


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;
}


来源:https://stackoverflow.com/questions/4013683/creating-generic-arrays-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!