Creating an array from two

4

I have the situation where I need to build a arrayC[] in Java from a arrayA[4] and a arrayB[7] , where arrayC[] must display arrayA[4] and then arrayB[7] :

For example:

arrayA[4] = {A0; A1; A2; A3};
arrayB[7] = {B0; B1; B2; B3; B4; B5; B6};
arrayC[i] = {A0; A1; A2; A3; B0; B1; B2; B3; B4; B5; B6};

How can I do this?

    
asked by anonymous 06.06.2018 / 19:04

2 answers

8

There are numerous ways to do this. One way is this:

XXX[] arrayC = new XXX[arrayA.length + arrayB.length];
for (int i = 0; i < arrayA.length; i++) {
    arrayC[i] = arrayA[i];
}
for (int i = 0; i < arrayB.length; i++) {
    arrayC[i + arrayA.length] = arrayB[i];
}

In the example above, XXX[] is the type of the array. This can be int[] , boolean[] , String[] , Object[] , etc.

Another way:

XXX[] arrayC = new XXX[arrayA.length + arrayB.length];
System.arraycopy​(arrayA, 0, arrayC, 0, arrayA.length);
System.arraycopy​(arrayB, 0, arrayC, arrayA.length, arrayB.length);

A third form, if the base type of the array is not a primitive type:

List<XXX> lista = new ArrayList<>();
lista.addAll(Arrays.asList(arrayA));
lista.addAll(Arrays.asList(arrayB));
XXX[] arrayC = lista.toArray(new XXX[0]);

A fourth form, using Stream s:

XXX[] arrayC = Stream.concat(Stream.of(arrayA), Stream.of(arrayB)).toArray(XXX[]::new);

See here all these forms working on ideone.

    
06.06.2018 / 19:12
4

In Java 8 onwards:

import java.util.*;
import java.util.stream.*;

public class HelloWorld{

    public static void main(String []args){
        int[] a = new int[] { 1, 2, 3 };
        int[] b = new int[] { 40, 50, 60 };

        int[] array =
            IntStream.concat(Arrays.stream(a), Arrays.stream(b))
                .toArray();

        System.out.println(Arrays.toString(array));
    }
}
    
06.06.2018 / 19:28