java 未定义数组类型的 copyOf 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2789193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:50:35  来源:igfitidea点击:

copyOf method undefined for the type Arrays

javaarraysobjectcopysystem

提问by Greg

elementData = Arrays.copyOf(elementData, newCapacity);

Gives error:

给出错误:

The method copyOf(Object[], int) is undefined for the type Arrays

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

This was not a problem on my home computer, but at my school's it gives the error above. I'm guessing it's running an older JRE version - any workaround?

这在我的家用电脑上不是问题,但在我学校的电脑上却出现了上述错误。我猜它正在运行旧的 JRE 版本 - 有什么解决方法吗?

回答by BalusC

From the javadocs:

javadocs

Since:
        1.6

自:
        1.6

So yes, your school is apparently using Java 1.5 or older. Two solutions are:

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

  1. Upgrade it (however, I'd first consult the school's system admin ;) ).
  2. Write your own utility method which does the same task (it's open source(line 2908)).
  1. 升级它(但是,我会先咨询学校的系统管理员;))。
  2. 编写您自己的实用方法来完成相同的任务(它是开源的(第 2908 行))。

回答by Brian Roach

Arrays.copyOf()was introduced in 1.6.

Arrays.copyOf()在 1.6 中引入。

You'd need to create a new array of the size you need and copy the contents of the old array into it.

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

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

来自: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; 
}

回答by akf

Arrays.copyOfwas introduced in 1.6. One work around would be to upgrade to 1.6. Another is to use System.arraycopy(see: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html)

Arrays.copyOf在 1.6 中引入。一种解决方法是升级到 1.6。另一种是使用System.arraycopy(见:http: //java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html

回答by bmargulies

Sounds like you have different versions of Java on different computers.

听起来您在不同的计算机上有不同版本的 Java。

Arrays.copyOfis new in Java 1.6.

Arrays.copyOf是新的Java 1.6