Write a static method named mergeLists that takes two ArrayLists of Integers as
ID: 3532136 • Letter: W
Question
Write a static method named mergeLists that takes two ArrayLists of Integers as parameters and returns a new ArrayList of Integers that contain the elements of the original lists "merged" together. By "merged" we mean interleaved going back and forth between the two input lists. For example, if the first list is [4, 7, 1] and the second list is [3, 9, 8], then the new list should be [4, 3, 7, 9, 1, 8]. If one list is longer than the other, append the remaining elements to the end of the new list
Explanation / Answer
public class HelloWorld
{
public static void main(String[] args)
{
int[] ar1={1,2,3};
int[] ar2={4,5,6};
int[] temp = new int[300];
int a1=ar1.length;
int a2=ar2.length;
int j=0,k=0;
for(int i=0;i<a1+a2;i++)
{
if(i%2==0)
{temp[i]=ar1[j];
j++;
}
else
{ temp[i]=ar2[k];
k++;
}
}
for(int i=0;i<a1+a2;i++)
{
System.out.println(temp[i]);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.