Arrays and generics don't really mix very well. This is because arrays are covariant , while generics are not. Let me give you an example:
public static void main(String args[]) { foo(new Float[1]); } public static void foo(Number[] n) { n[0] = 3; }
This code compiles, but will ArrayStoreException .
So, the problem that occurred while recreating this array is that it cannot be an AnyType array, but it can be a subclass of AnyType . Of course, you can use someArray.getClass() and create an array with reflection.
However, the general theme is that you should use List for arrays, because List do not have the same problems. Change the code to:
public static void main(String args[]) { foo(new ArrayList<Float>()); } public static void foo(List<Number> list) { list.add(3); }
And the code will not compile, which is much better.
source share