Java中如何把两个数组合并为⼀个
在Java中,如何把两个String[]合并为⼀个?jdk怎么使用
看起来是⼀个很简单的问题。但是如何才能把代码写得⾼效简洁,却还是值得思考的。这⾥介绍四种⽅法,请参考选⽤。⼀、apache-commons
这是最简单的办法。在apache-commons中,有⼀个ArrayUtils.addAll(Object[], Object[])⽅法,可以让我们⼀⾏搞定:String[] both = (String[]) ArrayUtils.addAll(first, second);
其它的都需要⾃⼰调⽤jdk中提供的⽅法,包装⼀下。
为了⽅便,我将定义⼀个⼯具⽅法concat,可以把两个数组合并在⼀起:
static String[] concat(String[] first, String[] second) {}
为了通⽤,在可能的情况下,我将使⽤泛型来定义,这样不仅String[]可以使⽤,其它类型的数组也可以使⽤:static <T> T[] concat(T[] first, T[] second) {}
当然如果你的jdk不⽀持泛型,或者⽤不上,你可以⼿动把T换成String。
⼆、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;
}
使⽤如下:
String[] both = concat(first, second);
三、pyOf()
在java6中,有⼀个⽅法pyOf(),是⼀个泛型函数。我们可以利⽤它,写出更通⽤的合并⽅法:
public static <T> T[] concat(T[] first, T[] second) {
T[] result = pyOf(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 = pyOf(first, totalLength);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
使⽤如下:
String[] both = concat(first, second);
String[] more = concat(first, second, third, fourth);
四、wInstance
还可以使⽤wInstance来⽣成数组:
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[]) flect.Array.
Class().getComponentType(), alen + blen);    System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。