Creating generic arrays in Java

前端 未结 3 527
情深已故
情深已故 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[] toArray() { 
    K[] array=(K[])Array.newInstance(claz,this.size());
    return array;
    }
    

提交回复
热议问题