一维数组的拷贝
1.for循环;
import java.util.Arrays;
public class TestDemo {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
int[] brr = new int[arr.length];
for (int i = 0;i < arr.length;i++) {
brr[i] = arr[i];
}
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(brr));
}
}
2.数组名.clone();
import java.util.Arrays;
public class TestDemo {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
int[] brr = arr.clone();
arr[0] = 10;
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(brr));
}
}
3.Arrays.copyOf();实现数组的扩容和缩容
查看Arrays类中copyOf函数
在copyOf函数中传入原数组original和新的数组长度newlength,在函数中先开辟一个和原数组数据类型相同的且长度为newlength数组,调用System.arraycopy()方法,从原数组的0号下标开始向新数组的0号下标开始复制,复制的长度为两个数组长度的最小值
public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
示例:
import java.util.Arrays;
public class TestDemo {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
int[] brr = Arrays.copyOf(arr,arr.length);
arr[0] = 10;
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(brr));
System.out.println("arr数组名保存:"+arr+" brr数组名保存:"+brr);
}
}
4. System.arraycopy(src, srcPos, dest, destPos, length);
import java.util.Arrays;
public class TestDemo {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
int[] brr = new int[arr.length];
System.arraycopy(arr,0,brr,0,arr.length);
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(brr));
System.out.println("arr数组名保存:"+arr+" brr数组名保存:"+brr);
}
}