一、for循环拷贝是最简单直观的方法,也是最low的方法,这里不做介绍。
二、使用 clone() 方法,使用clone方法进行拷贝时,是将arr中的所有元素都拷贝下来,不可以挑选。 clone() 方法的返回值是 Object 类型,要使用强制类型转换为适当的类型。
byte[] targetArray=(byte[])sourceArray.clone();
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
byte []data = {0,1,2,3,20,100,(byte)200,(byte)250};
byte []image = data.clone();
System.out.println("data :"+Arrays.toString(data));
System.out.println("image:"+Arrays.toString(image));
}
}
data :[0, 1, 2, 3, 20, 100, -56, -6]
image:[0, 1, 2, 3, 20, 100, -56, -6]
三、Arrays类中的 System.arraycopy方法
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
byte []data = {0,1,2,3,20,100,(byte)200,(byte)250};
byte []image = new byte[12];
System.arraycopy(data,2,image,1,3);
System.out.println("data :"+Arrays.toString(data));
System.out.println("image:"+Arrays.toString(image));
}
}
标准输出:
data :[0, 1, 2, 3, 20, 100, -56, -6]
image:[0, 2, 3, 20, 0, 0, 0, 0, 0, 0, 0, 0]
四、使用Arrays类中 CopyOfRange() 方法对数组进行复制该方法是Arrays 类中的 CopyOfRange() 方法,该方法用于拷贝某个范围.看其中的代码可以知道底层还是调用System.arraycopy方法。
Arrays.copyOfRange(dataType[] srcArray,int startIndex,int endIndex)
public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
byte []data = {0,1,2,3,20,100,(byte)200,(byte)250};
byte []image = Arrays.copyOfRange(data,2,5);
System.out.println("data :"+Arrays.toString(data));
System.out.println("image:"+Arrays.toString(image));
}
}
标准输出:
data :[0, 1, 2, 3, 20, 100, -56, -6]
image:[2, 3, 20]
nt[] original:将要拷贝的原数组
int from:拷贝数组的起始下标 ,下标值必须在 0 到原数组长度之间;
int to:拷贝数组的终止下标,且终止下标必须大于等于起始下标,也可以大于 arr.length,如果大于 arr.length,则新数组中剩余的空位置用默认值0进行填充。
上面复制的是【2到5),不包括5项。
五、Arrays类中的Arrays.copyOf方法,实现的方法也是调用System.arraycopy。
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
byte []data = {0,1,2,3,20,100,(byte)200,(byte)250};
byte []image = Arrays.copyOf(data,data.length-1);
System.out.println("data :"+Arrays.toString(data));
System.out.println("image:"+Arrays.toString(image));
}
}
标准输出:
data :[0, 1, 2, 3, 20, 100, -56, -6]
image:[0, 1, 2, 3, 20, 100, -56]
六、参考文章