Beliebige Anzahl Arrays zusammenfügen

chillerStudent

Bekanntes Mitglied
Hallo,

ich möchte eine beliebige Anzahl von int Arrays, die beliebig viele Indizes haben, zu einem Array fusionieren.

Java:
int[] a = {6,3,8};
int[] b = {9,5};
int[] c = {1,7,0};
int[] d = {4};
...
// beliebig viele Arrays

int[] e = new int[a.length+b.length];
		
		for(int i=0, j=0; i<=a.length-1; i++, j+=2) {
			e[j]=a[i];
		}
		
		int j=1;
		for(int i=0; i<=b.length-1; i++) {
			e[j]=b[i];
			if(i > a.length) {
				j++;
			} else {
				j+=2;
			}
		}

Bis zu zwei Arrays klappst ja, aber dann?? Danke schon mal für eure Hilfe!
 
du könntest den umweg über eine List gehen und diese anschließend in ein Array umwandeln
einfach eine Liste ArrayList<int> verknuepfen =new ArrayList<>();
und einfach alle arrays mit verknuepfen.add( array);
 
Oder du schreibst es dir selber.

Das geht einfach mit drei for-Schleifen und zwei int Variablen. Die erste Schleife addiert die Längen der Arrays und erstellt anhand derer das neue Array.
Die zweite Schleife ließt ein Array ein und die dritte, darin verschachtelte, Schleife kopiert die Einträge rüber, jedes Mal eine int Variable hochzählend, die den aktuellen Index im großen Array speichert.
 
Ich habs mal geschrieben:

Java:
class Test{
	
	static int a[] = new int[]{1, 2};
	static int b[] = new int[]{3, 4, 5, 6};
	static int c[] = new int[]{7, 8};
	static int d[] = new int[]{9};
	static int e[] = new int[]{10, 11, 12, 13, 14, 15};
	
	 public static void main(String args[]) {
		int[] x = concat(new int[][] {a, b, c, d, e});
		for(int i = 0; i < x.length; i++) System.out.println(x[i]);
	 }
	
	private static int[] concat(int[][] arr) {
		//Länge feststellen
		int length = 0;
		for(int i = 0; i < arr.length; i++) {
			length += arr[i].length;
		 }
		
		//Array erstellen und füllen
		int[] re = new int[length];
		int index = 0;
		for(int i = 0; i < arr.length; i++) {
			for(int j = 0; j < arr[i].length; j++) {
				re[index] = arr[i][j];
				index++;
			}
		}
		return re;
	}
}
 
Warum einfach, wenn es kompliziert geht?

Java:
import java.util.Arrays;

public class ArrayVersuche {

    static int a[] = new int[]{1, 2};
    static int b[] = new int[]{3, 4, 5, 6};
    static int c[] = new int[]{7, 8};
    static int d[] = new int[]{9};
    static int e[] = new int[]{10, 11, 12, 13, 14, 15};

	public static int[] concat(int[] first, int[] second) {
		int[] dest = new int[first.length + second.length];
		System.arraycopy(first, 0, dest, 0, first.length);
		System.arraycopy(second, 0, dest, first.length, second.length);		
		return dest;
	}

	public static int[] concat(int[] ... input) {
		int[] dest = {};
		for (int[] ia : input) {
			dest = concat(dest, ia);
		}
		return dest;
	}

	public static void main(String[] args) {
		int[] res = concat(a, b);
		System.out.println(Arrays.toString(res));
		res = concat(a, b, c, d, e);
		System.out.println(Arrays.toString(res));
	}
}
 

Neue Themen


Zurück
Oben