1, 将一个基本数据类型数组的引用赋值给另一个数组
- public class Array_copy {int[] array1=new int[]{1,2,3,4,5,6};
- int[] array2=array1;// 将 array1 的引用赋值给 array2, 两数组指向同一个内存空间
- public static void main(String args[]){
- Array_copy ac = new Array_copy();
- for (int i=0;i<ac.array1.length;i++){
- System.out.print(ac.array1[i]+" ");
- }
- System.out.println();
- for (int i=0;i<ac.array1.length;i++){
- System.out.print(ac.array2[i]+" ");
- }
- System.out.println("\n"+"修改数组 array1 的值, 查看 array2 是否改变");
- ac.array1[0]=10;// 修改数组第一元素
- for (int i=0;i<ac.array1.length;i++){
- System.out.print(ac.array1[i]+" ");
- }
- System.out.println();
- for (int i=0;i<ac.array1.length;i++){
- System.out.print(ac.array2[i]+" ");
- }
- }
- }
这里只是复制了数组的引用, 一个数组的改变会影响到另一个数组.
2, 使用 arraycopy 方法复制基本数据类型数组
2.1. arraycopy 方法声明
public static native void arraycopy(Object src,int srcPos,Object dest,int destPos,int lenhgth);
2.2. arraycopy 方法参数简介
src: 源数组
srcPos: 开始复制的位置, 从源数组哪个位置开始复制
dest: 目的数组
descPos: 将源数组复制到目标数组的起始位置
length: 复制多少个源数组中的元素个数
2.2. arraycopy 方法演示
- public class Arraycopy {
- int[] ary1 = new int[]{1, 2, 3, 4, 5, 6};
- int[] ary2 = new int[6];
- public void print(int[] array) {
- for (int i : array)
- System.out.print(i+" ");
- System.out.println();
- }
- /**
- * 使用 arraycopy 方法将数组 ary1 复制给 ary2
- * @param args
- */
- public static void main(String[] args) {
- Arraycopy ac = new Arraycopy();
- System.out.println("--- 两数组初始 ---");
- ac.print(ac.ary1);
- ac.print(ac.ary2);
- System.out.println("--- 将 ary1 复制给 ary2---");
- System.arraycopy(ac.ary1,0,ac.ary2,0,ac.ary1.length);
- ac.print(ac.ary1);
- ac.print(ac.ary2);
- System.out.println("--- 修改 ary1(ary2)查看 ary2(ary1)是否变化 ---");
- ac.ary1[0]=0;
- ac.print(ac.ary1);
- ac.print(ac.ary2);
- }
- }
使用 arraycopy 方法进行数组复制, 就不存在数组的引用, 即: 一个数组的内容的改变不会影响另一个数组的内容.
3, 对象类型 (引用类型) 数组的复制
- import java.awt.*;
- public class Arraycopy2 {
- /**
- * 定义对象数组
- */
- Label lb1[] = new Label[]{
- new Label("Label1"),
- new Label("Label2"),
- new Label("Label3")
- };
- Label lb2[] = new Label[lb1.length];
- public static void main(String args[]) {
- Arraycopy2 ac = new Arraycopy2();
- System.out.println("-- 将对象数组 lb1 复制给 lb2--");
- System.out.print("lb1 数组:");
- ac.print(ac.lb1);
- //ac.lb2 = ac.lb1;
- System.arraycopy(ac.lb1,0,ac.lb2,0,ac.lb1.length);
- System.out.print("lb2 数组:");
- ac.print(ac.lb2);
- System.out.println("\n-- 修改 lb1(lb2)查看 lb2(lb1)是否变化 --");
- ac.lb1[0].setText("Label0");
- System.out.print("lb1 数组:");
- ac.print(ac.lb1);
- System.out.print("lb2 数组:");
- ac.print(ac.lb2);// 修改 lb1 数组内容后发现 lb2 数组也发生改变, 说明 lb1 和 lb2 指向同一内存空间.
- // 当然修改 lb2 内容 lb1 内容也会改变, 这里不赘述了
- }
- public void print(Label[] lb) {
- for (Label i : lb) {
- System.out.print(i.getText() + " ");
- }
- System.out.println();
- }
- }
和基本类型数组是不同的, 当数组类型为对象类型时, 用 arraycopy 方法复制数组复制的也只是引用, 不是对象本身.
关联博客(CSDN): https://blog.csdn.net/m0_38022608/article/details/80262416
来源: https://www.cnblogs.com/qikeyishu/p/9021595.html