copyOf方法未定义类型数组

Gre*_*reg 3 java arrays copy system object

elementData = Arrays.copyOf(elementData, newCapacity);
Run Code Online (Sandbox Code Playgroud)

给出错误:

对于类型数组,方法copyOf(Object [],int)是未定义的

这在我的家用电脑上不是问题,但在我的学校,它给出了上述错误.我猜它正在运行一个较旧的JRE版本 - 任何解决方法?

Bal*_*usC 7

来自javadocs:

自:
        1.6

所以是的,你的学校显然使用Java 1.5或更早版本.两种解决方案是:

  1. 升级它(但是,我首先咨询学校的系统管理员;)).
  2. 编写自己的实用程序方法,它执行相同的任务(它的开源(第2908行)).


Bri*_*ach 5

Arrays.copyOf() 是在1.6中引入的.

您需要创建一个所需大小的新数组,并将旧数组的内容复制到其中.

来自:http://www.source-code.biz/snippets/java/3.htm

/**
* Reallocates an array with a new size, and copies the contents
* of the old array to the new array.
* @param oldArray  the old array, to be reallocated.
* @param newSize   the new array size.
* @return          A new array with the same contents.
*/
private static Object resizeArray (Object oldArray, int newSize) {
   int oldSize = java.lang.reflect.Array.getLength(oldArray);
   Class elementType = oldArray.getClass().getComponentType();
   Object newArray = java.lang.reflect.Array.newInstance(
         elementType,newSize);
   int preserveLength = Math.min(oldSize,newSize);
   if (preserveLength > 0)
      System.arraycopy (oldArray,0,newArray,0,preserveLength);

   return newArray; 
}
Run Code Online (Sandbox Code Playgroud)