English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à joindre deux tableaux en utilisant arraycopy et sans utiliser arraycopy en 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]
Dans le programme ci-dessus, nous avons deux tableaux d'entiers array1and array2.
Pour fusionner (joindre) deux tableaux, nous stockons respectivement leurs longueurs dans aLen et bLen. Ensuite, nous créons un tableau de longueur aLen + bLen dans un nouveau tableau d'entiers résultat.
Maintenant, pour les combiner, nous utilisons la fonction arraycopy() pour copier chaque élément des deux tableaux dans le résultat.
La fonction arraycopy(array1, 0, result, 0, aLen) indique simplement au programme de commencer à copier array1copier dans le résultat à partir de l'index 0 vers aLen.
De même, arraycopy(array2, 0, result, aLen, bLen) indique au programme de commencer à copier array2copier dans le résultat, à partir de l'index aLen vers 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 elements required for result, that is, the length of array1.length + array2. length. Then, we create a new length array result.
Now, we use for-each loop over array1of each element and store it in the result. After allocation, we increase the position pos1, pos ++.
Similarly, we iterate over the array2Perform the same operation and start from the array1Start storing each element of result from the position.