How to create a new AnyType [] array?

What is the best practice in this situation? I would like an un-initialized array of the same type and length as the original.

public static <AnyType extends Comparable<? super AnyType>> void someFunction(AnyType[] someArray) { AnyType[] anotherArray = (AnyType[]) new Comparable[someArray.length]; ...or... AnyType[] anotherArray = (AnyType[]) new Object[someArray.length]; ...some other code... } 

Thanks CB

+4
source share
3 answers
 AnyType[] anotherArray = (AnyType[])java.lang.reflect.Array.newInstance( someArray.getClass().getComponentType(), someArray.length); 
+7
source

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.

+5
source

A good reference is to see how <T> T[] Collection.toArray(T[]) is implemented by AbstractCollection :

 public <T> T[] toArray(T[] a) { // Estimate size of array; be prepared to see more or fewer elements int size = size(); T[] r = a.length >= size ? a : (T[])java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), size); //... 

Thus, the technique uses:

If you absolutely need to create a โ€œsharedโ€ array, then this method of passing instanceof T[] and using reflection to instantiate another is an example provided in the Java Framework.

However, you should also ask if you really need such features.

From Effective Java 2nd Edition: Clause 25: Prefers Array Lists :

So arrays and generics have very different type rules. Arrays are covariant and resuscitated, generics are invariant and erased. As a result, arrays provide runtime type security, but not compilation type security, and vice versa for generics. Generally speaking, arrays and generics do not mix well. If you find yourself mixing them up and get time errors and compilation warnings, your first impulse should be to replace arrays with lists.

You must read the entire subject for a more complete study of the subject.

+5
source

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


All Articles