views:

75

answers:

3
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 through 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.

A: 

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
You cannot create generic arrays directly. That's why I am asking...
ExtremeCoder
+1  A: 

Which Java version are you using? This code compiles and runs just fine for me:

import java.util.*;

public class Test<K> implements Iterable<K> {

    public static void main(String... args) {
        System.out.println(Arrays.toString(new Test<String>("a","b").toArray()));
        System.out.println(Arrays.toString(new Test<Integer>(1, 2).toArray()));
    }

    List<K> kList;

    Test(K... k) {
        kList = Arrays.asList(k);
    }

    private int size() {
        return kList.size();
    }

    @SuppressWarnings("unchecked")
    public K[] toArray() {
        K[] result = (K[])new Object[this.size()];
        int index  = 0;
        for(K k : this)
            result[index++] = k;
        return result;
    }

    public Iterator<K> iterator() {
        return kList.iterator();
    }
}
aioobe
Yes, but it will return a array of Objects, not an array of K
Maurice Perry
Oh, well you should have included more code in your question then...
aioobe
+4  A: 

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