使用其元素的类型重新分配数组大小

Reallocating array size using type of its element

我有一个 class 属性,它是一个 Anytype built-in 数组。在某些时候我需要重新分配它的内存来加倍它,但是因为它是 Anytype,我 不能做 :

myArray = new Anytype[myArray.length * 2];

由于数组已经定义,我可以访问它的元素class:

myArray[0].getClass();

我的问题是: 我可以利用我知道数组的 class 的事实来重新分配它吗?我知道我可以使用 Java utils 中的 Arrays.copyOf,但我想知道是否可以根据 object 需要的大小重新分配 类型的 C-way:

myArray = new myArray[0].getAllocationNeeded()[myArray.length * 2];

P.S:不知道标题是否相关,有更清楚的请指出

是的,像这样(假设源不为 null 或空):

   public <T> T[] resizeArray(T[] source, int multiplier) {
    T[] newArray = (T[]) Array.newInstance(source.getClass().getComponentType(), source.length * multiplier);
    System.arraycopy(source, 0, newArray, 0, source.length);
    return newArray;
}

两者:

  • source.getClass().getComponentType()
  • myArray[0].getClass()

Return 元素 class。