Итак, у вас есть два массива A и B , и вам нужно скопировать элементы A в B. Ну, есть различные способы, которыми вы можете сделать это на Java, и в этом посте я покажу вам пару способов, которыми вы можете это сделать.
Способ первый: ForLoop Этот старый добрый for-loop спешит на помощь:
int[] A = {1,2,4,4}; int[] B = new int[]; for (int i = 0; i < A.length; i++){ B[i] = A[i]; }
Способ второй: .clone()
Метод clone массива может помочь вам просто достичь этого.
Использование
int[] A = {1,2,4,4}; int[] B = A.clone();//the clone method copies the content of A into B;
Способ третий: System.arraycopy()
Следующий вариант – использовать метод System.arraycopy(), присутствующий в пакете java.lang
. Прежде чем мы перейдем к его использованию, давайте обсудим его подпись:
public static void arraycopy( Object src, //:source array, in this case A int srcPos, //:the start index for copy, typically 0 Object dest, //:destination object in this case B. int destPos, //:the index to place the copied elements int length //:the length of the contents to be copied );
Использование
int[] A = {1,2,4,4}; int[] B = new int[]; System.arraycopy(A, 0, B, 0, A.length);
Способ четвертый: Arrays.copyOf()
Следующий вариант, который мы будем обсуждать, относится к классу Arrays, присутствующему в пакете java.utils
. Еще раз давайте обсудим его подпись:
public static int[] copyOf( int[] original, // :source array in this case A int newLength // :the length of the contents to be copied );
Использование
int[] A = {1,2,4,4}; int[] B = Arrays.copyOf(A, 3);
Метод пятый: Arrays.copyOfRange()
Итак, это будет последний вариант, который мы будем обсуждать в этом посте и из класса Arrays, присутствующего в пакете java.utils
. Еще раз, давайте посмотрим на его подпись:
public static int[] copyOfRange( int[] original, // :source array in this case A int from, //:the start index for copy, typically 0 int to // the end index exclusive );
Использование
int[] A = {1,2,3,4,5,6,7}; int[] B = Arrays.copyOfRange(A, 0, A.length);
Оригинал: “https://dev.to/imanuel/how-to-copy-array-in-java-56go”