Java two arrays merge into one array

1. int[] array

int[] a = {1,2,6};
int[] b = {7,8,9};

The combined result is:

[1, 2, 6, 7, 8, 9] 

2. String[] array

String[] a = {"阿","java","so","easy"};
String[] b = {"is","very","good"};

The combined result is:

[阿, java, so, easy, is, very, good]

Method 1: Use a for loop

1. Use two for loops to copy the elements in array a and array b to array c

2. The first for loop copies the elements in array a to the first half of array c

3. The second for loop copies the elements in array b to the second half of array c

// int[]数组
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
    c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
    c[a.length +i] = b[i];
}
// String[]数组
String[] c = new String[a.length + b.length];
for (int i = 0; i < a.length; i++) {
    c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
    c[a.length + i] = b[i];
}

Method 2: Use the Arrays.copyOf() method 

1. Use the Arrays.copyOf () method to create a new array, and copy the elements in array a to array c

2. Use the System.arraycopy () method to copy the elements in array b to the second half of array c.

// int[]数组
int[] c = Arrays.copyOf(a,a.length+b.length);
System.arraycopy(b,0,c,a.length,b.length);
// String[]数组
String[] c = Arrays.copyOf(a,a.length+b.length);
System.arraycopy(b,0,c,a.length,b.length);

Method 3: Use the IntStream.concat method

1. Use the Arrays.stream() method to convert array a and array b into IntStream objects

2. Use the Stream.concat() method to connect the two IntStream objects into a single stream

3. Use the toArray() method to convert the concatenated stream into an array c

// int[]数组
int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b)).toArray();
// String[]数组
Object[] c = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray();

Method 4: Use the System.arraycopy() method

1. The first System.arraycopy() method copies the elements in array a to the first half of array c

2. The second System.arraycopy() method copies the elements in array b to the second half of array c.

方法:System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

Parameters:
src – the source array.

srcPos – The starting position in the source array.

dest – the destination array.

destPos – The starting position in the destination data.

length – the number of array elements to copy

// int[]数组
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);
// String[]数组
String[] c = new String[a.length + b.length];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,a.length,b.length);

Guess you like

Origin blog.csdn.net/SUMMERENT/article/details/131211918