T...">

Two methods for creating shared arrays

I learned about two methods for creating shared arrays.

One

@SuppressWarnings("unchecked") static <T> T[] array1(final Class<T> elementType, final int size) { return (T[]) Array.newInstance(elementType, size); } 

And the other

 static <T> T[] array2(final Class<T[]> arrayType, final int size) { return arrayType.cast(Array.newInstance(arrayType.getComponentType(), size)); } 

What's better? Are they the same (internally)? Is any case wrong?

+4
source share
3 answers

Behind the scenes, both do the same, except that in option 1 you pass an object of class T , and in option 2 you pass in T [].

I prefer option 1 because it is shorter and easier to read. Again, this is the same as Array.newInstance with the addition of a throw, so I'm not sure if your method adds more value. Array.newInstance

+5
source

Please note that the first one is not type safe. For example, the following raises a ClassCastException:

 array1(int.class, 5); 
+2
source

Another (best) way to create shared arrays

 @SafeVarargs static <E> E[] newArray(int length, E... array) { return Arrays.copyOf(array, length); } Integer[] ints = newArray(10); String[] strings = newArray(10); 
0
source

Source: https://habr.com/ru/post/1487194/


All Articles