Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two integer arrays [duplicate]

Tags:

java

arrays

Is there a way to create a single array out of two? E.g.

int[] array1 = {1,2,3}; int[] array2 = {4,5,6}; int[] array1and2 = array1 + array2; 
like image 781
Jon Avatar asked Jan 15 '11 00:01

Jon


People also ask

How do you combine two integer arrays?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do I merge two arrays without duplicates?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates. filter() is used to identify if an item is present in the “merged_array” or not. Just like the traditional for loop, filter uses the indexOf() method to judge the occurrence of an item in the merged_array.


1 Answers

You can't add them directly, you have to make a new array and then copy each of the arrays into the new one. System.arraycopy is a method you can use to perform this copy.

int[] array1and2 = new int[array1.length + array2.length]; System.arraycopy(array1, 0, array1and2, 0, array1.length); System.arraycopy(array2, 0, array1and2, array1.length, array2.length); 

This will work regardless of the size of array1 and array2.

like image 136
Kaleb Brasee Avatar answered Oct 04 '22 06:10

Kaleb Brasee