轉自:http://blog.csdn.net/jaycee110905/article/details/9179227java
在Java中,如何把兩個String[]
合併爲一個?apache
看起來是一個很簡單的問題。可是如何才能把代碼寫得高效簡潔,卻仍是值得思考的。這裏介紹四種方法,請參考選用。數組
1、apache-commons
這是最簡單的辦法。在apache-commons中,有一個ArrayUtils.addAll(Object[], Object[])
方法,可讓咱們一行搞定:app
String[] both = (String[]) ArrayUtils.addAll(first, second);
其它的都須要本身調用jdk中提供的方法,包裝一下。函數
爲了方便,我將定義一個工具方法concat
,能夠把兩個數組合並在一塊兒:工具
static String[] concat(String[] first, String[] second) {}
爲了通用,在可能的狀況下,我將使用泛型來定義,這樣不只String[]
可使用,其它類型的數組也可使用:oop
static <T> T[] concat(T[] first, T[] second) {}
固然若是你的jdk不支持泛型,或者用不上,你能夠手動把T換成String
。spa
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;
- }
使用以下:.net
String[] both = concat(first, second);
3、Arrays.copyOf()
在java6中,有一個方法Arrays.copyOf()
,是一個泛型函數。咱們能夠利用它,寫出更通用的合併方法:rest
- 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;
- }
使用以下:
String[] both = concat(first, second); String[] more = concat(first, second, third, fourth);
4、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;
- }