Метод System.arraycopy()

Метод System.arraycopy() осуществляет копирование части массива в другой массив.

Рассмотрим пример, копирующий элементы 2,3,4 из массива arraySource в массив arrayDestination:

import java.util.Arrays;

public class ArrayCopy1 {
    public static void main(String[] args) {
        int[] arraySource = {1, 2, 3, 4, 5, 6};
        int[] arrayDestination = {0, 0, 0, 0, 0, 0, 0, 0};

        System.out.println("arraySource: " + Arrays.toString(arraySource));
        System.out.println("arrayDestination: "
                + Arrays.toString(arrayDestination));

        System.arraycopy(arraySource, 1, arrayDestination, 2, 3);
        System.out.println("arrayDestination after arrayCopy: "
                + Arrays.toString(arrayDestination));
    }
}

Результат выполнения:

arraySource: [1, 2, 3, 4, 5, 6]
arrayDestination: [0, 0, 0, 0, 0, 0, 0, 0]
arrayDestination after arrayCopy: [0, 0, 2, 3, 4, 0, 0, 0]

Можно копировать в тот же массив с перекрытием областей:

import java.util.Arrays;

public class ArrayCopy2 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println(Arrays.toString(array));

        System.arraycopy(array, 1, array, 3, 3);
        System.out.println(Arrays.toString(array));
    }
}

Результат выполнения:

[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 2, 3, 4, 7, 8]

Презентацию с видео можно скачать на Patreon.

Read also:
Trustpilot
Trustpilot
Comments
hmma0723
Jun 17, 2017
How about the transaction rollback? When a transaction is rollback, the persistence context is cleared. The managed entities become detached.