How can I concatenate two arrays in Java?
To concatenate two arrays in Java, you can use the System.arraycopy
method. Here's an example of how you can do this:
int[] a = {1, 2, 3};
int[] b = {4, 5, 6};
int[] c = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
This will create a new array c
that contains the elements of a
followed by the elements of b
.
Alternatively, you can use the Arrays.copyOf
method to create a new array that is the combined length of a
and b
, and then use a loop to copy the elements of a
and b
into the new array:
int[] a = {1, 2, 3};
int[] b = {4, 5, 6};
int[] c = Arrays.copyOf(a, a.length + b.length);
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
This will also create a new array c
that contains the elements of a
followed by the elements of b
.
Note that these approaches will create a new array that is the combined length of a
and b
. They do not modify the original arrays. If you want to modify one of the original arrays, you can use a loop to copy the elements of the other array into it.