How can I concatenate two arrays in Java?

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

提交回复
热议问题