Java實現把兩個數組合並為一個的方法總結


本文實例講述了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 static String[] concat(String[] a, String[] b) {
2   String[] c= new String[a.length+b.length];
3 
4   System.arraycopy(a, 0, c, 0, a.length);
5   System.arraycopy(b, 0, c, a.length, b.length);
6 
7   return c;
8 
9 }

使用如下:

1 String[] both = concat(first, second);

三、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;
}

如果要合並多個,可以這樣寫:

 1 public static <T> T[] concatAll(T[] first, T[]... rest) {
 2      int totalLength = first.length;
 3 
 4      for (T[] array : rest) {
 5           totalLength += array.length;
 6      }
 7 
 8      T[] result = Arrays.copyOf(first, totalLength);
 9      int offset = first.length;
10 
11      for (T[] array : rest) {
12           System.arraycopy(array, 0, result, offset, array.length);
13           offset += array.length;
14      }
15 
16      return result;
17 }

使用如下:

String[] both = concat(first, second);
String[] more = concat(first, second, third, fourth);

四、Array.newInstance

還可以使用Array.newInstance來生成數組:

 1     private static <T> T[] concat(T[] a, T[] b) {
 2         final int alen = a.length;
 3         final int blen = b.length;
 4 
 5         if (alen == 0) {
 6             return b;
 7         }
 8         if (blen == 0) {
 9             return a;
10         }
11 
12         final T[] result = (T[]) java.lang.reflect.Array.
13                 newInstance(a.getClass().getComponentType(), alen + blen);
14         System.arraycopy(a, 0, result, 0, alen);
15         System.arraycopy(b, 0, result, alen, blen);
16 
17         return result;
18     }

希望本文所述對大家java程序設計有所幫助。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM