Java System.arraycopy

Java System.arraycopy

从指定源数组中进行拷贝操作,可以指定开始位置,拷贝指定长度的元素到指定目标数组中。该方法是一个本地静态方法,声明如下:

public static native void arraycopy(Object src, int srcPos,
                                    Object dest, int destPos,
                                    int length);
src: the source array.
srcPos: source array index from where copy will start
dest: the destination array.
destPos: destination array index from where data will be copied.
length: the number of elements to copy.
import java.util.Arrays; 

int[] source = { 1, 2, 3, 4, 5, 6, 7 };
int[] destination = new int[5];

System.arraycopy(source, 3, destination, 2, 3); // 要复制的源数组中的元素为 4,5,6。 这些将从索引2开始复制到目标数组。
System.out.println(Arrays.toString(destination)); // [0, 0, 4, 5, 6]

当源和目标是相同的阵列时,将从源阵列创建一个临时阵列。 然后将临时数组中的元素复制到源数组。

int[] source = { 1, 2, 3, 4, 5, 6, 7 };
System.arraycopy(source, 3, source, 5, 2); 
System.out.println(Arrays.toString(source)); // [1, 2, 3, 4, 5, 4, 5]

arraycopy() 方法有5个参数。 因此,在许多情况下会发生异常。 此方法引发的异常是:

NullPointerException: if source or destination array is null.
ArrayStoreException: if the source and destination array type doesn’t match or they are not array.
ArrayIndexOutOfBoundsException: if the data overflow occurs because of index values or they are negative.

一般会有如下四种方式对数组进行拷贝:

  • for 遍历,遍历源数组并将每个元素赋给目标数组。
  • clone 方法,原数组调用 clone 方法克隆新对象赋给目标数组,更深入的克隆可以看之前的文章《从JDK角度看对象克隆》
  • System.arraycopy,JVM 提供的数组拷贝实现。
  • Arrays.copyof,实际也是调用 System.arraycopy。

System.arraycopy 为 JVM 内部固有方法,它通过手工编写汇编或其他优化方法来进行 Java 数组拷贝,这种方式比起直接在 Java 上进行 for 循环或 clone 是更加高效的。数组越大体现地越明显。

2022. 将一维数组转变成二维数组

Leetcode
知识点: Array 复制的方法 for, System.arraycopy, Arrays.copyOfRange. 空数组。

class Solution {
    public int[][] construct2DArray(int[] original, int m, int n) {   
       
        if (original.length != m * n) return new int[0][]; // new int[][]{};
        int[][] res = new int[m][n];
        // for (int i = 0; i < m; i++){
        //     for (int j = 0; j < n; j++){
        //         res[i][j] = original[i * n + j];
        //     }
        // }
        for (int i = 0; i < original.length; i += n) {
            // System.arraycopy(original, i, res[i / n], 0, n);
            res[i / n] = Arrays.copyOfRange(original, i, i + n);
        }
        return res;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值