Java配列のコピー-System.arraycopy()およびArrays.copyOf()

これらの2つの関数は、多くの場合、ArrayListソースコードに含まれています。

 public static void main(String[] args)
    {
    
    
        int[] arr = {
    
    1,2,3,4,5,6,7};
        System.arraycopy(arr,2,arr,4,3);
        for (int i = 0; i < arr.length; i++)
        {
    
    
            System.out.println(arr[i]);
        }
    }
输出
1
2
3
4
3
4
5

結果から、ゼロからのカウントは元の配列の4番目(4番目を含む)からコピーされ、コピーされたコンテンツは配列の2番目(2番目を含む)からの3つの数字であることがわかります。

Arrays.copyOf()原码:

    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;
    }

Arrays.copyOf()がSystem.arraycopy()関数を呼び出すことがソースコードからわかります。これは、両方の配列がゼロからコピーされ、コピーのサイズが2つの配列の最小長であることを意味します。
コード:

    public static void main(String[] args)
    {
    
    
        int[] arr = {
    
    1,2,3,4,5,6,7};
        int[] tmp = Arrays.copyOf(arr, 10);
        for (int i = 0; i < tmp.length; i++)
        {
    
    
            System.out.println(tmp[i]);
        }
    }
输出
1
2
3
4
5
6
7
0
0
0

おすすめ

転載: blog.csdn.net/weixin_43663421/article/details/109336867