Array verbinden, mit und ohne new

Mathias1000

Mitglied
Ich habe da 2 Beispiele, einmal mit new und mal ohne new.
Beide Proceduren machen das gleiche.
Spielt es eine Rolle, ob ich die Stringe ohne new erzeuge ?
Das Programm läuft auch ohne new ohne Fehler.
Java:
package stringarray;

import java.util.Arrays;

public class ArraysVerbinden {

	void verbinde1() {
		String[][] arr1 = { new String[] { "00", "01", "02" },
				new String[] { "10", "11", "12" },
				new String[] { "20", "21", "22" } };
		String[][] arr2 = { new String[] { "aa", "ab", "ac" },
				new String[] { "ba", "bb", "bc" },
				new String[] { "ca", "cb", "cc" } };

		int newLength = arr1.length + arr2.length;
		String[][] s = new String[newLength][3];
		s = Arrays.copyOf(arr1, newLength);
		System.arraycopy(arr2, 0, s, arr1.length, arr2.length);

		for (int i = 0; i < s.length; i++) {
			for (int j = 0; j < s[i].length; j++) {
				System.out.print(s[i][j]);
			}
		}
		System.out.println();
	}

	static void verbinde2() {
		String[][] arr1 = { { "00", "01", "02" }, { "10", "11", "12" },
				{ "20", "21", "22" } };
		String[][] arr2 = { { "aa", "ab", "ac" }, { "ba", "bb", "bc" },
				{ "ca", "cb", "cc" } };

		int newLength = arr1.length + arr2.length;
		String[][] s;
		s = Arrays.copyOf(arr1, newLength);
		System.arraycopy(arr2, 0, s, arr1.length, arr2.length);

		for (int i = 0; i < s.length; i++) {
			for (int j = 0; j < s[i].length; j++) {
				System.out.print(s[i][j]);
			}
		}
		System.out.println();
	}

	public static void main(String[] args) {
		new ArraysVerbinden().verbinde1();
		verbinde2();
	}
}
 
Ne, macht keinen Unterschied, siehe Quellcode:

Code:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
 

Zurück
Oben