logo CodeStepByStep logo

indexOfAll

Language/Type: Java ArrayList collections
Related Links:

Write a method named indexOfAll that accepts two ArrayLists of integers a1 and a2 as parameters and that returns a new ArrayList of integers representing all starting indexes where a2's sequence of elements appear in a1. The sequence of elements in a2 may appear anywhere in a1 but must appear consecutively and in the same order. For example, if variables called a1 and a2 store the following values:

//   index
//   0  1  2  3  4  5  6  7  8  9 10 11
a1: [1, 6, 1, 2, 1, 4, 1, 2, 1, 2, 1, 8]
a2: [1, 2, 1]

Then the call of indexOfAll(a1, a2) should return the list [2, 6, 8] because a2's sequence of values [1, 2, 1] is contained in a1 starting at those indexes. Any two lists with identical elements are considered to contain each other, so a call such as indexOfAll(a1, a1) should return [0]. If a1 does not contain a2, return an empty list.

You may assume that both lists passed to your method will have lengths of at least 1. You may not use any strings to help you solve this problem, nor methods that produce strings such as toString on a list.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.