Gre*_*reg 3 java arrays copy system object
elementData = Arrays.copyOf(elementData, newCapacity);
Run Code Online (Sandbox Code Playgroud)
给出错误:
对于类型数组,方法copyOf(Object [],int)是未定义的
这在我的家用电脑上不是问题,但在我的学校,它给出了上述错误.我猜它正在运行一个较旧的JRE版本 - 任何解决方法?
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)