Java: copying arrays of non basic types

What is the preferred way to copy non primitive arrays in Java? How about performance issues?

Solution

The old school is:

public static void java.lang.System.arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

This is copied from one existing array to another You must assign a new array yourself... Suppose you are making a copy of the array

Starting with JDK 6, Java util. The arrays class has many copyof methods for making copies of arrays with new sizes Relevant are:

public static <T> T[] copyOf(T[] original,int newLength)

and

public static <T,U> T[] copyOf(U[] original,int newLength,Class<? extends T[]> newType)

The first uses the original array type to copy, and the second uses a different array type to copy

Note that both arraycopy and 3 parameter copyof must check the type of each element in the original (source) array according to the target array type So both can throw type exceptions 2 the parameter copyof (at least in theory) does not require any type checking, so it should be (theoretically) faster In practice, the relative performance will depend on the implementation For example, array replication is usually handled specially by the JVM

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>