English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste programa, você aprenderá a conectar dois arrays usando arraycopy e sem usar arraycopy no Java.
import java.util.Arrays; public class Concat { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int aLen = array1.length; int bLen = array2.length; int[] result = new int[aLen + bLen]; System.arraycopy(array1, 0, result, 0, aLen); System.arraycopy(array2, 0, result, aLen, bLen); System.out.println(Arrays.toString(result)); } }
When running the program, the output is:
[1, 2, 3, 4, 5, 6]
No programa acima, temos dois arrays inteiros array1and array2.
Para combinar (juntar) dois arrays, armazenamos suas respectivas larguras em aLen e bLen. Em seguida, criamos um array de comprimento aLen + bLen de novo array inteiro resultado.
Agora, para combinar os dois, usamos a função arraycopy() para copiar cada elemento dos dois arrays para o resultado.
função arraycopy(array1, 0, result, 0, aLen) informa simplesmente ao programa que comece a copiar do índice 0 o array1Copie para o resultado a partir do índice 0 até aLen.
Da mesma forma, arraycopy(array2, 0, result, aLen, bLen) informa ao programa que comece a copiar do índice 0 o array2Copie para o resultado, a partir do índice aLen até bLen.
import java.util.Arrays; public class Concat { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int length = array1.length + array2.length; int[] result = new int[length]; int pos = 0; for (int element : array1) { result[pos] = element; pos++; } for (int element : array2) { result[pos] = element; pos++; } System.out.println(Arrays.toString(result)); } }
When running the program, the output is:
[1, 2, 3, 4, 5, 6]
In the above program, we did not use arraycopy, but manually copied the array array1and array2each element to result.
We store the total number of lengths required for result, that is, the length of array1.length + array2. length. Then, we create a new array of results with a new length.
Now, we use for-each loop traverses the array1of each element and store it in the result. After allocation, we increase the position pos1, pos ++.
Similarly, we process the array2Perform the same operation and start from the array1Start storing each element of result from the position.