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;
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With