Inside, you create an array of "Object" instead of an array of "C"
Try this code:
public static <C> C[] method(int number) { return new Object() { C[] create(int length, C ... cs) { return Arrays.copyOf(cs, length); } }.create(number); } public static void main(String[] args) { System.out.println(Main.<Integer>method(10)); System.out.println(new Integer[10]); }
[Ljava.lang.Object; @ 6bc7c054
[Ljava.lang.Integer; @ 232204a1
As you can see, they do not match.
This is dangerous because if you run something like this:
public static void main(String[] args) { Integer[] integerArray1 = Main.<Integer>method(10); Integer[] integerArray2 = new Integer[10]; }
And you will have a ClassCastException
[Ljava.lang.Object; cannot be applied to [Ljava.lang.Integer
If you want to create any array, you need to send a class to build the array, you can do it as follows:
public static <C> C[] method(Class<C> clazz, int number) { return (C[]) Array.newInstance(clazz, number); } public static void main(String[] args) { Integer[] integerArray1 = Main.<Integer>method(Integer.class, 10); Integer[] integerArray2 = new Integer[10]; }
source share