2010-10-23 28 views
1

在Java中將多個String []合併爲一個String []的最佳方式是什麼?在Java中合併String []

+0

什麼是你的 「最好」 的定義是什麼? – 2010-10-23 17:35:57

回答

2

只是另一種可能性:

public static String[] mergeStrings(String[]...matrix){ 
    int total = 0; 
     for(String[] vector : matrix){ 
      total += vector.length; 
     } 
     String[] resp = new String[total]; 

     for(int i=0; i< matrix.length; i++){ 
      for(int j=0; j< matrix[i].length; j++){ 
       resp[i*matrix.length + j] = matrix[i][j]; 
      } 
     } 
     return resp; 
} 

你不能測試:

public static void main(String[] args) { 
     String[] resp =mergeStrings(new String[]{"1","2"}, new String[]{"3", "4", "5"}); 
     for(String s : resp) 
      System.out.println(s); 
} 
+0

+1很好的解決方案。 – helpermethod 2010-10-23 18:10:23

4

那麼,你會作出一個單一的[]等於所有的[]一起的大小,然後調用System.arraycopy

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#arraycopy(java.lang.Object,INT,java.lang.Object中,INT,INT

將每個人移動到新的大陣列。

這將是o(n),其中n是您要組合的字符串的數量。

更好的問題是,你的代碼是否真的如此重要,以至於你使用arrayList數組?在大多數情況下ArrayList更容易處理,應該在[]上使用。

+0

我必須給一個我沒有自己寫過的API給一個String []。 – Christian 2010-10-23 17:27:54

0

使用java.util.Arrays中創建一個集合,然後返回列表:)

String[] moo1 = {"moo", "moo2"}; 
    String[] moo2 = {"moo3", "moo4"}; 
    String[] moo3 = {"moo5", "moo5"}; 

    ArrayList<String> strings = new ArrayList<String>(); 
    strings.addAll(Arrays.asList(moo1)); 
    strings.addAll(Arrays.asList(moo2)); 
    strings.addAll(Arrays.asList(moo3)); 
    String[] array = strings.toArray(new String[0]); 
+1

代碼中的'Arrays#asList()'將返回'List ',而不是'List ',正如您所期望的那樣。 – BalusC 2010-10-23 17:53:25

+0

@BalusC - 對不起:( – willcodejavaforfood 2010-10-23 17:59:27

+0

更好,但我更喜歡'系統#arrayCopy()':)(我沒有downvote順便說一句)。 – BalusC 2010-10-23 18:18:38

2

我建議使用System#arraycopy()而不是平臺本地操作(因此yiel DS更好的性能):

public static String[] concat(String[]... arrays) { 
    int length = 0; 
    for (String[] array : arrays) { 
     length += array.length; 
    } 
    String[] newArray = new String[length]; 
    int pos = 0; 
    for (String[] array : arrays) { 
     System.arraycopy(array, 0, newArray, pos, array.length); 
     pos += array.length; 
    } 
    return newArray; 
} 

更多泛型:

public static <T> T[] concat(Class<T> type, T[]... arrays) { 
    int length = 0; 
    for (T[] array : arrays) { 
     length += array.length; 
    } 
    T[] newArray = (T[]) Array.newInstance(type, length); 
    int pos = 0; 
    for (T[] array : arrays) { 
     System.arraycopy(array, 0, newArray, pos, array.length); 
     pos += array.length; 
    } 
    return newArray; 
} 

使用示例:

String[] arr1 = { "foo1", "bar1" }; 
String[] arr2 = { "foo2", "bar2", "baz2" }; 
String[] arr3 = { "foo3" }; 

String[] all1 = concat(arr1, arr2, arr3); 
System.out.println(Arrays.toString(all1)); // [foo1, bar1, foo2, bar2, baz2, foo3] 

String[] all2 = concat(String.class, arr1, arr2, arr3); 
System.out.println(Arrays.toString(all2)); // [foo1, bar1, foo2, bar2, baz2, foo3]