.
3ss.cn

java怎么复制数组

1、数组长度相等

假设nums和nums1是长度相等的两个数组。

(推荐教程:java课程)

1.1、用nums = nums1;

赋值前

赋值后

nums创建的时候在堆里面创建一块内存区域用来存储,nums指向这个内存地址A。nums1创建后指向B。

现在令nums = nums1;则把num1的地址(或者说是引用)赋给了num,所以num也指向了B。两个数组都指向堆中同一个内存区域,他们是共享里面的数据。

1.2、for循环

        for (int i = 0; i < nums1.length; i++){
            nums[i] = nums1[i];
        }

循环前

循环后

成功改变nums数组内部内容,而没有改变其引用。

1.3、Arrays类

方法1:复制指定数组至指定长度

nums = Arrays.copyOf(nums1,5);

方法2:复制指定数组的指定长度

nums = Arrays.copyOfRange(nums1,0,5);

两种方法最后的索引都可以>数组的长度,然后后面的都会补上0。

两种方法都可以成功复制数组,而且我们发现原数组nums从524变成了526,说明这两种复制方法是创建了一个新数组,然后用等号左边的数组指向这个新数组。

1.4、System.arraycopy方法

System.arraycopy(originalArray, 0, targetArray, 0, originalArray.length);

可以看出这个方法类似于我们的for循环,是直接改原来数组的内容,没有改引用。

2、数组长度不等

赋值法成功for循环要注意越界问题,会报java.lang.ArrayIndexOutOfBoundsExceptionArrays类法成功注意越界问题,会报java.lang.ArrayIndexOutOfBoundsException

其他:

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

   //思路:设置一个index,表示非0数的个数,循环遍历数组,
    // 如果不是0,将非0值移动到第index位置,然后index + 1
    //遍历结束之后,index值表示为非0的个数,再次遍历,从index位置后的位置此时都应该为0
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[index] = nums[i];
                index++;
            }
        }

        for (int i = index; i < nums.length; i++) {
            nums[i] = 0;
        }
    }
赞(0)
未经允许不得转载:互联学术 » java怎么复制数组

评论 抢沙发