I'm new to Java, and I know there are way better ways to concatenate two arrays like using IntStream.concat method, but as I want to learn, I just preferred to do it in this way
I'm trying to concatenate two arrays of integers using below function
public static int[] mergeAndOrder(int[] array1, int[] array2) {
int [] tmp= new int [array1.length+ array2.length];
int k=array1.length;
for(int i=0; i<array1.length; i++)
{
tmp[i]=array1[i];
}
for(int i=0; i< array2.length; i++)
{
tmp[k]=array2[i];
k++;
}
return tmp;
}
is it correct?
it seems it did not concatenate two arrays of integers
I think your approach should work. I wrote a simple test to prove it:
@Test
public void test()
{
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
int[] expected = {1, 2, 3, 2, 3, 4};
int[] actual = mergeAndOrder(a, b);
log.info(Arrays.toString(a));
log.info(Arrays.toString(b));
log.info(Arrays.toString(actual));
assertThat(actual, is(expected));
}
My log statements seem to agree:
2023-06-19 13:48:34,953 INFO [] (main) [1, 2, 3]
2023-06-19 13:48:34,968 INFO [] (main) [2, 3, 4]
2023-06-19 13:48:34,968 INFO [] (main) [1, 2, 3, 2, 3, 4]
Like user16320675, I am wondering why you think it did not concatenate the two arrays; it appears to work.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments