SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arraylists
Exercise:
Exercises
Question:16 | ISBN:9780136091813 | Edition: 2

Question

Write a method called interleave that accepts two ArrayList s 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] .

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of interleave method:

	public static void interleave(ArrayList intList1,
			ArrayList intList2)
	{
		int i = 1; // for intList1
		int j = 0; // for intList2
		
		while(j < intList2.size())
		{
			if(i < intList1.size())
			{
				intList1.add(i, intList2.get(j));
				i += 2;
			}
			else
			{
				intList1.add(intList2.get(j));
				i++;
			}

			j++;
		}
	}
0 0

Discussions

Post the discussion to improve the above solution.