在Java 中如何合并同类型的数组呢?
比如我有三个int类型的数组,分别是
int[] a = { 1, 2, 3 };
int[] b = { 4, 5 };
int[] c = { 6, 8 };
想合并为一个大的数组,怎么办呢?
- public static int[] mergeArray(int[]... a) {
- // 合并完之后数组的总长度
- int index = 0;
- int sum = 0;
- for (int i = 0; i < a.length; i++) {
- sum = sum + a[i].length;
- }
- int[] result = new int[sum];
- for (int i = 0; i < a.length; i++) {
- int lengthOne = a[i].length;
- //拷贝数组
- System.arraycopy(a[i], 0, result, index, lengthOne);
- index = index + lengthOne;
- }
- return result;
- }
- //测试方法,把a、b、c三个数组合并为result(同类型的数组,长度为三个数组长度总和)
- @Test
- public void testMerge() {
- int[] a = { 1, 2, 3 };
- int[] b = { 4, 5 };
- int[] c = { 6, 8 };
- int[] result = mergeArray(a, b, c);
- for (int i = 0; i < result.length; i++) {
- System.out.print(result[i] + " ");
- }
- System.out.println();
- System.out.println("length:"+result.length);
- }