How can I concatenate two arrays in Java?

后端 未结 30 1984
走了就别回头了
走了就别回头了 2020-11-21 06:05

I need to concatenate two String arrays in Java.

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

What is t

30条回答
  •  独厮守ぢ
    2020-11-21 06:50

    Here a possible implementation in working code of the pseudo code solution written by silvertab.

    Thanks silvertab!

    public class Array {
    
       public static  T[] concat(T[] a, T[] b, ArrayBuilderI builder) {
          T[] c = builder.build(a.length + b.length);
          System.arraycopy(a, 0, c, 0, a.length);
          System.arraycopy(b, 0, c, a.length, b.length);
          return c;
       }
    }
    

    Following next is the builder interface.

    Note: A builder is necessary because in java it is not possible to do

    new T[size]

    due to generic type erasure:

    public interface ArrayBuilderI {
    
       public T[] build(int size);
    }
    

    Here a concrete builder implementing the interface, building a Integer array:

    public class IntegerArrayBuilder implements ArrayBuilderI {
    
       @Override
       public Integer[] build(int size) {
          return new Integer[size];
       }
    }
    

    And finally the application / test:

    @Test
    public class ArrayTest {
    
       public void array_concatenation() {
          Integer a[] = new Integer[]{0,1};
          Integer b[] = new Integer[]{2,3};
          Integer c[] = Array.concat(a, b, new IntegerArrayBuilder());
          assertEquals(4, c.length);
          assertEquals(0, (int)c[0]);
          assertEquals(1, (int)c[1]);
          assertEquals(2, (int)c[2]);
          assertEquals(3, (int)c[3]);
       }
    }
    

提交回复
热议问题