Creating generic arrays in Java

前端 未结 3 526
情深已故
情深已故 2020-12-18 09:30
public K[] toArray()
{
    K[] result = (K[])new Object[this.size()];
    int index  = 0;
    for(K k : this)
        result[index++] = k;
    return result;
}


        
相关标签:
3条回答
  • 2020-12-18 09:51

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 09:58

    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.

    0 讨论(0)
  • 2020-12-18 10:07

    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;
    }
    
    0 讨论(0)
提交回复
热议问题