Java – a common way to write duplicate arrays
For my programming task, I was asked to write a general copy method to copy from an array to an array of the same size and type Is this even possible in Java? Everything I tried ended up with some "generic array creation" errors I'm lost. I don't know how to solve this problem!
public class copyArray<AnyType>{ public copyArray(AnyType[] original){ AnyType[] newarray = new AnyType[original.length]; for(int i =0; i<original.length; i++){ newarray[i] = original[i]; } }
resolvent
Solution
You can use the concept of reflection to write generic replication methods that can determine types at run time In short, reflection is the ability to check classes, interfaces, fields and methods at run time without knowing the names of classes, methods, etc. at compile time
java. Lang. reflect and Java Lang. class together constitute the java reflection API This method uses these two classes and some of their methods to create a generic arraycopy method that will find the type for us
More information: what is reflection and why is it useful?
Possibly unfamiliar grammar
>Class Use wildcard operators? Basically, we can have a class object of unknown type - the general version of class. >< T> Is a general operator, representing the raw type > arraythe array class, which provides static methods for dynamically creating and accessing Java arrays That is, this class contains methods that allow you to set and query the values of array elements, determine the length of the array, and create new array instances We will use array newInstance()
Reflection API method
>GetClass () – returns an array containing class objects that represent all public classes and interfaces that are members of the represented class object. > Getcomponenttype() - returns a class representing the component type (type, i.e. int, etc.) of the array. > Newinstance() - get a new instance of the array
private <T> T[] arrayCopy(T[] original) { //get the class type of the original array we passed in and determine the type,store in arrayType Class<?> arrayType = original.getClass().getComponentType(); //declare array,cast to (T[]) that was determined using reflection,use java.lang.reflect to create a new instance of an Array(of arrayType variable,and the same length as the original T[] copy = (T[])java.lang.reflect.Array.newInstance(arrayType,original.length); //Use System and arraycopy to copy the array System.arraycopy(original,copy,original.length); return copy; }