For my programming assignment, I was asked to write a generic copy method to copy from one array to an identically sized and typed array. Is this even possible in Java? Everything I tried ended up with some "generic array creation" error. I am lost and 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]; }
}
You can use the concept of reflection to write a generic copy method that can determine type at runtime. In a nutshell, reflection is the ability to inspect classes, interfaces, fields and methods at runtime without knowing the names of classes, methods etc at compile time.
java.lang.Reflect together with java.lang.Class comprise the Java Reflection API. This method uses both of those classes and some of their methods to make a generic arrayCopy
method that will find out the type for us.
More info: What is reflection and why is it useful?
Class<?>
is using a wildcard operator ?
which basically says that we can have a Class
object of unknown type - a generic version of class Class
.<T>
is a generic operator that stands for raw type
Array
The Array class provides static methods to dynamically create and access Java arrays. i.e. 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 instances of arrays. We are going to use Array.newInstance()
getClass ()
- returns an array containing Class objects representing all public classes and interfaces that are members of the represented class object.getComponentType()
- returns the class representing the component type (what type i.e. int, , etc) of the array.newInstance()
- Gets a new instance of an 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, 0, copy, 0, original.length);
return copy;
}
Much simpler solution would be to use existing clone()
method of any array (unless your assignment tells explicitly not to use clone()
):
public static <T> T[] arrayCopy(T[] original) {
return original.clone();
}
Actually you don't need such generic helper method at all, you can call the clone()
method directly (and it will work for primitive arrays as well).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With