您的位置:首页 > 编程语言 > Java开发

Java中把两个数组合并为一个

2012-09-06 18:19 393 查看
把两个
String[]
合并为一个:

void f(String[] first, String[] second) {
    String[] both = ???
}

看起来是一个很简单的问题。但是如何才能把代码写得高效简洁,却还是值得思考的。

首先是System.arraycopy()

T[] concat(T[] A, T[] B) {
   T[] C= new T[A.length+B.length];
   System.arraycopy(A, 0, C, 0, A.length);
   System.arraycopy(B, 0, C, A.length, B.length);

   return C;
}

注意,其中的泛型
T
必须换成一个实际的类,才能通过编译,因为
new T[length]
在java中是不允许的。

Arrays.copyOf()

在java6中,有一个方法
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;
}
         

Array.newInstance

可以使用
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;
}
         

apache-commons

在apache-commons中,有一个
ArrayUtils.addAll(Object[], Object[])
方法,可以让我们一行搞定:

String[] both = (String[]) ArrayUtils.addAll(first, second);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java string rest object c