How can I concatenate two arrays in Java?

后端 未结 30 2027
走了就别回头了
走了就别回头了 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:29

    Here's a simple method that will concatenate two arrays and return the result:

    public <T> T[] concatenate(T[] a, T[] b) {
        int aLen = a.length;
        int bLen = b.length;
    
        @SuppressWarnings("unchecked")
        T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
        System.arraycopy(a, 0, c, 0, aLen);
        System.arraycopy(b, 0, c, aLen, bLen);
    
        return c;
    }
    

    Note that it will not work with primitive data types, only with object types.

    The following slightly more complicated version works with both object and primitive arrays. It does this by using T instead of T[] as the argument type.

    It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.

    public static <T> T concatenate(T a, T b) {
        if (!a.getClass().isArray() || !b.getClass().isArray()) {
            throw new IllegalArgumentException();
        }
    
        Class<?> resCompType;
        Class<?> aCompType = a.getClass().getComponentType();
        Class<?> bCompType = b.getClass().getComponentType();
    
        if (aCompType.isAssignableFrom(bCompType)) {
            resCompType = aCompType;
        } else if (bCompType.isAssignableFrom(aCompType)) {
            resCompType = bCompType;
        } else {
            throw new IllegalArgumentException();
        }
    
        int aLen = Array.getLength(a);
        int bLen = Array.getLength(b);
    
        @SuppressWarnings("unchecked")
        T result = (T) Array.newInstance(resCompType, aLen + bLen);
        System.arraycopy(a, 0, result, 0, aLen);
        System.arraycopy(b, 0, result, aLen, bLen);        
    
        return result;
    }
    

    Here is an example:

    Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));
    Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));
    
    0 讨论(0)
  • This is a converted function for a String array:

    public String[] mergeArrays(String[] mainArray, String[] addArray) {
        String[] finalArray = new String[mainArray.length + addArray.length];
        System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);
        System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);
    
        return finalArray;
    }
    
    0 讨论(0)
  • 2020-11-21 06:30

    If you use this way so you no need to import any third party class.

    If you want concatenate String

    Sample code for concate two String Array

    public static String[] combineString(String[] first, String[] second){
            int length = first.length + second.length;
            String[] result = new String[length];
            System.arraycopy(first, 0, result, 0, first.length);
            System.arraycopy(second, 0, result, first.length, second.length);
            return result;
        }
    

    If you want concatenate Int

    Sample code for concate two Integer Array

    public static int[] combineInt(int[] a, int[] b){
            int length = a.length + b.length;
            int[] result = new int[length];
            System.arraycopy(a, 0, result, 0, a.length);
            System.arraycopy(b, 0, result, a.length, b.length);
            return result;
        }
    

    Here is Main method

        public static void main(String[] args) {
    
                String [] first = {"a", "b", "c"};
                String [] second = {"d", "e"};
    
                String [] joined = combineString(first, second);
                System.out.println("concatenated String array : " + Arrays.toString(joined));
    
                int[] array1 = {101,102,103,104};
                int[] array2 = {105,106,107,108};
                int[] concatenateInt = combineInt(array1, array2);
    
                System.out.println("concatenated Int array : " + Arrays.toString(concatenateInt));
    
            }
        }  
    

    We can use this way also.

    0 讨论(0)
  • 2020-11-21 06:30

    A generic static version that uses the high performing System.arraycopy without requiring a @SuppressWarnings annotation:

    public static <T> T[] arrayConcat(T[] a, T[] b) {
        T[] both = Arrays.copyOf(a, a.length + b.length);
        System.arraycopy(b, 0, both, a.length, b.length);
        return both;
    }
    
    0 讨论(0)
  • 2020-11-21 06:35

    You can append the two arrays in two lines of code.

    String[] both = Arrays.copyOf(first, first.length + second.length);
    System.arraycopy(second, 0, both, first.length, second.length);
    

    This is a fast and efficient solution and will work for primitive types as well as the two methods involved are overloaded.

    You should avoid solutions involving ArrayLists, streams, etc as these will need to allocate temporary memory for no useful purpose.

    You should avoid for loops for large arrays as these are not efficient. The built in methods use block-copy functions that are extremely fast.

    0 讨论(0)
  • 2020-11-21 06:37

    This should be one-liner.

    public String [] concatenate (final String array1[], final String array2[])
    {
        return Stream.concat(Stream.of(array1), Stream.of(array2)).toArray(String[]::new);
    }
    
    0 讨论(0)
提交回复
热议问题