Creating shared arrays in Java

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 work, it will throw an exception:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be added to ...

Can someone tell me how can I create an array with a common type? Thanks.

+4
source share
3 answers

You cannot: 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; } 
+11
source

Your code throws this exception because it actually gives you an array of type Object . Maurice Perry's code works, but casting to K[ ] will result in a warning, since the compiler cannot guarantee type safety in this case due to type erasure. However, you can 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 a safe type guarantee. How this works is explained in detail in my answer with a similar question some time ago.

+1
source

Well, this does not work K [] result = new K [this.size ()];

If you could hold a class. Then:

  Class claz; Test(Class m) { claz = m; } <K> K[] toArray() { K[] array=(K[])Array.newInstance(claz,this.size()); return array; } 
0
source

All Articles