简介
本文用示例介绍Java如何创建数组对象、如何合并多个数组为一个数组。
新建数组
基本类型
int[] a = new int[5]; //指定长度
int[] b = new int[]{1, 2, 3}; //指定初始值
数组与可变参数
可变参数其实就是数组,如下:
package org.example.a;
public class Demo {
public static void main(String[] args){
addTest(1, 2, 3);
//下边这样写一样的效果
//addTest(new int[]{1, 2, 3});
addTest("Result is", 1,2);
}
public static void addTest(int... args) {
int sum = 0;
for (int arg : args) {
sum += arg;
}
System.out.println(sum);
}
public static void addTest(String str, int... args) {
int sum = 0;
for (int arg : args) {
sum += arg;
}
System.out.println(sum);
}
}
执行结果
6 Result is:3
合并数组
法1:Arrays.copyOf
public static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
合并多个,可以这样写:
public static <T> T[] concatAll(T[] first, T[]... rest) {
int totalLength = first.length;
for (T[] array : rest) {
totalLength += array.length;
}
T[] result = Arrays.copyOf(first, totalLength);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
法2:System.arraycopy()
static String[] concat(String[] a, String[] b) {
String[] c= new String[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
法3.Array.newInstance
private static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
if (alen == 0) {
return b;
}
if (blen == 0) {
return a;
}
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
法4:apache-commons
这是最简单的方法,一行搞定。
String[] both = (String[]) ArrayUtils.addAll(first, second);

请先 !