Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method called alternate that accepts two Lists of integers as its parame

ID: 3938147 • Letter: W

Question

Write a method called alternate that accepts two Lists of integers as its parameters and returns a new List containing alternating elements from the two lists, in the following order: First element from first list First element from second list Second element from first list Second element from second list Third element from first list Third element from second list ... If the lists do not contain the same number of elements, the remaining elements from the longer list should be placed consecutively at the end. For example, for a first list of (1, 2, 3, 4, 5) and a second list of (6, 7, 8, 9, 10, 11, 12), a call of alternate(listl, list2) should return a list containing (1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 11, 12). Do not modify the parameter lists passed in. This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

Explanation / Answer

Here is the code for you:

import java.util.ArrayList;
import java.util.Arrays;
public class MergeArrayListsAlternately {
public static void main(String[] args)
{
ArrayList a = new ArrayList();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(5);
ArrayList b = new ArrayList();
b.add(6);
b.add(7);
b.add(8);
b.add(9);
b.add(10);
b.add(11);
b.add(12);
System.out.println(alternate(a, b));
  
}
public static ArrayList alternate(ArrayList a, ArrayList b)
{
ArrayList comb = new ArrayList(a.size() + b.size());
int j = 0;
int k = 0;
int l = 0;
int max = Math.max(a.size(),b.size());
for (int i = 0; i < max; i++)
{
if (j < a.size())
{
comb.add(l++, a.get(j++));
}
if (k < b.size())
{
comb.add(l++, b.get(k++));
}
}
return comb;
  
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote