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

Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merg

ID: 3672021 • Letter: W

Question

Write a method
public static ArrayList merge(ArrayList a, ArrayList b)
that merges two array lists, alternating elements from both array lists. If one array
list is shorter than the other, then alternate as long as you can and then append the
remaining elements from the longer array list. For example, if a is
1 4 9 16
and b is
9 7 4 9 11
then merge returns the array list
1 9 4 7 9 4 16 9 11

Please use the template below: Dr.java

/**
* Auto Generated Java Class.
*/
import java.util.ArrayList;

public class arrayListLab
{
public static void main(String[] args)
{
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
  
// Initialize array list a to some values
for (int i = 0; i < 4; i++)
{
a.add((i + 1) * (i + 1));
}
// Initialize array list b to some values
b.add(9);
b.add(7);
b.add(4);
b.add(9);
b.add(11);
b.add(21);
System.out.println("ArrayList b is "+b);
System.out.println("ArrayList a is " +a);
System.out.println("merge returns "+merge(a,b));
  
}
public static ArrayList merge(ArrayList x, ArrayList y)
{
// create a merging algorithm and code.
ArrayList temp = new ArrayList(x.size()+y.size());
  
for(Integer i :x)
{
temp.add(i);
}
for(Integer i : y)
{
temp.add(i);
}
return(temp);
}
}

Explanation / Answer

import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ArraylistMerge { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ArrayList listA = new ArrayList(); ArrayList listB = new ArrayList(); ArrayList listC = new ArrayList(); listA.add(1); listA.add(4); listA.add(6); listA.add(7); listB.add(2); listB.add(3); listB.add(4); listB.add(7); listC.add(1); listC.add(2); listC.add(4); listC.add(7); listC.add(9); ArrayList lists = new ArrayList(); lists.add(listA); lists.add(listB); lists.add(listC); ArrayList listIndex = new ArrayList(); int numOfElements = 0; for(int i = 0; i
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