第一种方式也是最常见的方式:for循环
public class Test {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
int[] newarr = copyOf(arr);
System.out.println(Arrays.toString(newarr));
}
public static int[] copyOf(int[] arr) {
int[] arr2 = new int[arr.length];
for (int i = 0; i <arr.length;i ++) {
arr2[i] = arr [i];
}
return arr2;
}
}
返回一个字符串要用System.out.println(Arrays.toString(newarr));
返回;方法里面如果有返回值,要用int[ ]作为方法返回值;int[] arr2 = new int[arr.length];
这块着重记住。
第二种方式:copyOf
public class Test {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int[] ret = Arrays.copyOf(arr,arr.length-2);
//arr表示拷贝的数组,arr.length-2,表示数组的长度
System.out.println(Arrays.toString(ret));
}
}
通过int[] ret = Arrays.copyOf(arr,arr.length-2);
进行拷贝,再用最后一行代码输出。
第三种方法:arraycopy
public class Test {
public static void main(String[] args) {
int[] arr = {1,2,3};
int[] ret = new int[arr.length];
System.arraycopy(arr,0,ret,0,arr.length);
System.out.println(Arrays.toString(ret));
}
}
arraycopy的用法如下:(拷贝速度最快)
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos, int length);
native:表示这是本地的方法;
src:源数组;
srcPos:从源数组的pos位置开始拷贝;
dest:拷贝到的目的数组;
destPos:拷贝到目的数组的pos位置;
length:拷贝的长度
第四种方法:clone(产生需要克隆的对象的副本)
public class Test {
public static void main(String[] args) {
int[] arr = {1,2,3};
int[] ret = arr.clone();
System.out.println(Arrays.toString(ret));
}
}