本文實例講述了Java實現把兩個數組合并為一個的方法。分享給大家供大家參考,具體如下:
在Java中,如何把兩個String[]合并為一個?
看起來是一個很簡單的問題。但是如何才能把代碼寫得高效簡潔,卻還是值得思考的。這里介紹四種方法,請參考選用。
一、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()
1
2
3
4
5
6
|
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; } |
使用如下:
1
|
String[] both = concat(first, second); |
三、Arrays.copyOf()
在java6中,有一個方法Arrays.copyOf()
,是一個泛型函數。我們可以利用它,寫出更通用的合并方法:
1
2
3
4
5
|
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; } |
如果要合并多個,可以這樣寫:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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; } |
使用如下:
1
2
|
String[] both = concat(first, second); String[] more = concat(first, second, third, fourth); |
四、Array.newInstance
還可以使用Array.newInstance
來生成數組:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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; } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/jaycee110905/article/details/9179227