Java将两个数组合并成一个新的数组

package practice;

public class AnArrayOfMerger {

	public static void main(String[] args) {

		String arr[] = { "1", "2", "3", "4", "5" };
		String brr[] = { "a", "b", "c", "d" };
		String buildArray[] = new String[arr.length + brr.length];

		int indexArr = 0; // 手动指定arr的下标
		int indexBrr = 0; // 手动指定brr的下标
		for (int i = 0; i < buildArray.length; i++) {
			if (i < arr.length) {
				// 循环变量 i 小于 arr.length 时,将arr中的元素赋值给新数组
				buildArray[i] = arr[indexArr];
				indexArr++;
			} else {
				/**
				 * 循环变量 i 的值大于 arr.length 时,此时新数组下标 i 必定大于brr.length 
				 * 继续循环将brr中的元素赋值给新数组
				 */
				if (i > brr.length) {
					buildArray[i] = brr[indexBrr];
					indexBrr++;
				}
			}
		}

		System.out.print("数组arr中的元素:");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "    ");
		}

		System.out.print("\n\n数组brr中的元素:");
		for (int i = 0; i < brr.length; i++) {
			System.out.print(brr[i] + "    ");
		}

		System.out.print("\n\n数组合并后:");
		for (int i = 0; i < buildArray.length; i++) {
			System.out.print(buildArray[i] + "    ");
		}

	}

}

你可能感兴趣的:(典化成籍-Java)