Java: Copy array of non-primitive type(Java:复制非原始类型的数组)
问题描述
在 Java 中复制非原始类型数组的首选方法是什么?性能问题呢?
What is the prefered way to copy an array of a non-primitve type in Java? How about performance issues?
推荐答案
老派的做法是:
public static void java.lang.System.arraycopy(Object src, int srcPos,
Object dest, int destPos, int length)
这会从一个现有数组复制到另一个数组.您必须自己分配新数组...假设您正在制作一个数组的副本.
This copys from one existing array to another. You have to allocate the new array yourself ... assuming that you are making a copy of an array.
从 JDK 6 开始,java.util.Arrays 类有许多 copyOf 方法用于制作具有新大小的数组副本.相关的是:
From JDK 6 onwards, the java.util.Arrays class has a number of copyOf methods for making copies of arrays, with a new size. The ones that are relevant are:
public static <T> T[] copyOf(T[] original, int newLength)
和
public static <T,U> T[] copyOf(U[] original, int newLength,
Class<? extends T[]> newType)
第一个使用原始数组类型进行复制,第二个使用不同的数组类型进行复制.
This first one makes a copy using the original array type, and the second one makes a copy with a different array type.
请注意,arraycopy 和 3 参数 copyOf 都必须根据目标数组类型检查原始(源)数组中每个元素的类型.所以两者都可以抛出类型异常.2 参数 copyOf (至少在理论上)不需要进行任何类型检查,因此应该(理论上)更快.在实践中,相对性能将取决于实现.例如,arraycopy 经常被 JVM 给予特殊处理.
Note that both arraycopy and the 3 argument copyOf have to check the types of each of the elements in the original (source) array against the target array type. So both can throw type exceptions. The 2 argument copyOf (in theory at least) does not need to do any type checking and therefore should be (in theory) faster. In practice the relative performance will be implementation dependent. For instance, arraycopy is often given special treatment by the JVM.
这篇关于Java:复制非原始类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:复制非原始类型的数组
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
