Java的:非基本类型的数组复制 [英] Java: Copy array of non-primitive type

查看:148
本文介绍了Java的:非基本类型的数组复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是prefered方式复制非primitve型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)

这copys从一个现有阵列到另一个。你必须自己分配新数组......假设你正在一个的的副本的数组。

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的:非基本类型的数组复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆