4
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.

DJClayworth
  • 24,627
  • 8
  • 50
  • 71
ExtremeCoder
  • 4,069
  • 4
  • 38
  • 55

3 Answers3

11

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;
}
Maurice Perry
  • 31,563
  • 8
  • 67
  • 95
1

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.

Community
  • 1
  • 1
gdejohn
  • 6,648
  • 1
  • 30
  • 45
0

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;
}
Gadolin
  • 2,494
  • 3
  • 22
  • 33