There are numerous ways to do this. One of the ways 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 above example, 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 way, 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 way, using Stream
s:
XXX[] arrayC = Stream.concat(Stream.of(arrayA), Stream.of(arrayB)).toArray(XXX[]::new);
See here all these ways working on ideone.
The types of
arrayA
andarrayB
are the same?– Marcelo Shiniti Uchimura
are yes, the two are int
– Lucas Monteiro