编写通用方法来复制数组

Mik*_*idt 3 java arrays copy

对于我的编程任务,我被要求编写一个通用的复制方法,从一个数组复制到相同大小和类型的数组.这在Java中甚至可能吗?我尝试的一切都以一些"通用数组创建"错误结束.我迷路了,不知道怎么解决这个问题!

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]; } 
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*eue 5

您可以使用反射的概念来编写可以在运行时确定类型的通用复制方法.简而言之,反射是在运行时检查类,接口,字段和方法的能力,而无需在编译时知道类,方法等的名称.

java.lang.reflect中连同java.lang.Class中包括Java反射API.此方法使用这两个类及其一些方法来创建一个通用arrayCopy方法,以便为我们找出类型.

更多信息:什么是反射,为什么它有用?

可能不熟悉的语法

  • Class<?>正在使用通配符运算符?,它基本上表示我们可以拥有一个Class未知类型的对象 - 类的通用版本Class.
  • <T> 是一个代表原始类型的通用运算符
  • ArrayArray类提供动态创建和访问Java数组的静态方法.ie此类包含的方法允许您设置和查询数组元素的值,确定数组的长度,以及创建新的数组实例.我们打算用Array.newInstance()
  • 反射API的方法

  • getClass () - 返回一个包含Class对象的数组,这些对象表示作为所表示的类对象成员的所有公共类和接口.
  • getComponentType() - 返回表示数组的组件类型(类型,即int等)的类.
  • newInstance() - 获取数组的新实例.
  • 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;
    }
    
    Run Code Online (Sandbox Code Playgroud)