Arrays zusammenfügen

angie0408

Mitglied
Hallo ich habe hier einen Code geschrieben, der zwei Arrays zu einem Array zusammen fügt.
Meine Frage ist nun, ob es auch einen schnelleren und kürzeren Weg dafür gibt?
Java:
public class arrayschleifen {

   public static void main(String[] args) {


       int[] a = {1, 2, 25};
       int[] b = {9, 18};
       int[] c = new int[5];
      
       c[0] = a[0];
       c[1] = a[1];
       c[2] = a[2];
       c[3] = b[0];
       c[4] = b[1];
      
      
   for (int durchlauf : c)
       System.out.print(durchlauf + " ");

   }

}
Danke schonmal im Voraus 🙂
 
Zuletzt bearbeitet von einem Moderator:
Ja da gibts mehrere, such dir eine aus:
Java:
int[] a = {1, 2, 25};
int[] b = {9, 18};
int[] c = new int[5];

// 1
int index = 0;
for (int i : a) c[index++] = i;
for (int i : b) c[index++] = i;

System.out.println(Arrays.toString(c));

// 2
c = IntStream.concat(IntStream.of(a), IntStream.of(b)).toArray();

System.out.println(Arrays.toString(c));

// 3
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);

System.out.println(Arrays.toString(c));
 
Du kannst, das ganze leichter mit einer for-Schleife lösen.

Java:
public static final int[] combine(int[] array1, int[] array2) {
    int[] combinedArray = new int[array1.length + array2.length];

    for(int index = 0; index < array1.length; index++) {
        combinedArray[index] = array1[index];
    }

    for(int index = 0; index < array2.length; index++) {
        combinedArray[index + array1.length] = array2[index];  // Die länge des ersten Arrays muss auf den Index addiert werden um die Position des Elements im zusammengesetzten Array zu bestimmen.
    }

    return combinedArray;
}
 

Zurück
Oben