elementData = Arrays.copyOf(elementData, newCapacity);
出现错误:
方法copyOf(Object[], int)在类型Arrays中未定义
这在我的家用电脑上不是问题,但在学校的电脑上出现了上述错误。我猜测它正在运行更旧的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;
}
Arrays.copyOf
是在1.6版本中引入的。一个解决方法是升级到1.6版本。另一个方法是使用 System.arraycopy
(参见:http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html)。
听起来你在不同的计算机上安装了不同版本的Java。
Arrays.copyOf
是在 Java 1.6
中新增的。