如何在Java中鏈接兩個數組?

我須要在Java中串聯兩個String數組。 數組

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

最簡單的方法是什麼? ide


#1樓

一個簡單的變體,能夠鏈接多個數組: spa

public static String[] join(String[]...arrays) {

    final List<String> output = new ArrayList<String>();

    for(String[] array : arrays) {
        output.addAll(Arrays.asList(array));
    }

    return output.toArray(new String[output.size()]);
}

#2樓

請原諒我爲這個已經很長的列表添加了另外一個版本。 我查看了每一個答案,並決定我真的想要一個簽名中僅包含一個參數的版本。 我還添加了一些參數檢查功能,以便在乎外輸入的狀況下從早期失敗中得到明智的信息。 code

@SuppressWarnings("unchecked")
public static <T> T[] concat(T[]... inputArrays) {
  if(inputArrays.length < 2) {
    throw new IllegalArgumentException("inputArrays must contain at least 2 arrays");
  }

  for(int i = 0; i < inputArrays.length; i++) {
    if(inputArrays[i] == null) {
      throw new IllegalArgumentException("inputArrays[" + i + "] is null");
    }
  }

  int totalLength = 0;

  for(T[] array : inputArrays) {
    totalLength += array.length;
  }

  T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);

  int offset = 0;

  for(T[] array : inputArrays) {
    System.arraycopy(array, 0, result, offset, array.length);

    offset += array.length;
  }

  return result;
}

#3樓

哇! 這裏有不少複雜的答案,包括一些依賴於外部依賴性的簡單答案。 這樣作是如何的: get

String [] arg1 = new String{"a","b","c"};
String [] arg2 = new String{"x","y","z"};

ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(arg1));
temp.addAll(Arrays.asList(arg2));
String [] concatedArgs = temp.toArray(new String[arg1.length+arg2.length]);

#4樓

思考問題的另外一種方式。 要鏈接兩個或多個數組,必需要作的就是列出每一個數組的全部元素,而後構建一個新的數組。 這聽起來像建立List<T> ,而後在其上調用toArray 。 其餘一些答案使用ArrayList ,那很好。 可是如何實施咱們本身的呢? 這並不難: input

private static <T> T[] addAll(final T[] f, final T...o){
    return new AbstractList<T>(){

        @Override
        public T get(int i) {
            return i>=f.length ? o[i - f.length] : f[i];
        }

        @Override
        public int size() {
            return f.length + o.length;
        }

    }.toArray(f);
}

我相信以上等效於使用System.arraycopy解決方案。 可是我認爲這有它本身的美麗。 io


#5樓

ArrayList<String> both = new ArrayList(Arrays.asList(first));
both.addAll(Arrays.asList(second));

both.toArray(new String[0]);
相關文章
相關標籤/搜索