concatenate java arrays [closed]

1

I have been asked for a two arrays, I have found this tool (int[])ArrayUtils.addAll(a, b) that I can solve in a single line. The problem is that the compiler gives me error

  

C: \ Users \ BEEO \ Desktop \ java \ practice3> javac Vector.java   . \ OperationVectores.java: 23: error: can not find symbol            int [] c = (int []) ArrayUtils.addAll (a, b);                           ^ symbol: variable ArrayUtils location: class OperacionVectores 1 error

import java.util.Arrays;
public class OperacionVectores{
public int[] ConcatV(int[] a, int[] b){
    int[] c= (int[])ArrayUtils.addAll(a, b);
    return c;

 }

}

Thank you very much for your time

    
asked by Barly Espinal 29.06.2018 в 03:05
source

1 answer

6

That method you are using belongs to the Apache Commons and is not available in the JDK . That's why the compiler can not find it.

I put a method that would be valid in base Java:

public int[] concatV(int[] left, int[] right) {
    int[] result = new int[left.length + right.length];

    System.arraycopy(left, 0, result, 0, left.length);
    System.arraycopy(right, 0, result, left.length, right.length);

    return result;
}

Use System.arraycopy that internally verifies that you are using an array and iterates by copying the values.

Another way to do it from Java 8 is to use the api of Streams :

public int[] concatV2(int[] left, int[] right) {
    return IntStream.concat(IntStream.of(left), IntStream.of(right)).toArray();
}
    
answered by 29.06.2018 в 08:29