Write a method called interleave that accepts two ArrayLists of integers a1 and
ID: 3650240 • Letter: W
Question
Write a method called interleave that accepts two ArrayLists of integers a1 and a2 as parameters and inserts the elements of a2 into a1 at alternating indexes. If the lists are of unequal length, the remaining elements of the longer list are left at the end of a1. For example, if a1 stores [10, 20, 30] and a2 stores [4, 5, 6, 7, 8], the call of interleave(a1, a2); should change a1 to store [10, 4, 20, 5, 30, 6, 7, 8]. If a1 had stored [10, 20, 30, 40, 50] and a2 had stored [6, 7, 8], the call of interleave(a1, a2); would change a1 to store [10, 6, 20, 7, 30, 8, 40, 50].Explanation / Answer
Please rate...
Program interLeave.java
=============================================================
import java.util.ArrayList;
class interLeave
{
public static void main(String args[])
{
ArrayList a1=new ArrayList();
ArrayList a2=new ArrayList();
a1.add(10);a1.add(20);a1.add(30);
a2.add(4);a2.add(5);a2.add(6);
a2.add(7);a2.add(8);a2.add(9);
int i;
System.out.println("Before interleaving:");
System.out.print("a1=[");
for(i=0;i<a1.size();i++)
{
System.out.print(a1.get(i)+" ");
}
System.out.print("] ");
System.out.print("a2=[");
for(i=0;i<a2.size();i++)
{
System.out.print(a2.get(i)+" ");
}
System.out.print("] ");
InterLeave(a1,a2);
System.out.println("After interleaving:");
System.out.print("a1=[");
for(i=0;i<a1.size();i++)
{
System.out.print(a1.get(i)+" ");
}
System.out.print("] ");
}
public static void InterLeave(ArrayList a1, ArrayList a2)
{
ArrayList a3=new ArrayList();
int i;
for(i=0;i<(a1.size()>a2.size()?a1.size():a2.size());i++)
{
if(i<a1.size())a3.add(a1.get(i));
if(i<a2.size())a3.add(a2.get(i));
}
a1.clear();
a1.addAll(a3);
}
}
==========================================================
Sample output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.