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

Find the positions of all strings equal to a given string in an array list of st

ID: 3574876 • Letter: F

Question

Find the positions of all strings equal to a given string in an array list of strings. Adapt the algorithm from Section 7.7. Instead of stopping at the first match, collect all positions. Complete the following code.

Use the following file:

Tester.java

Complete the following file:

ArrayListUtil.java

import java.util.ArrayList;

public class ArrayListUtil
{
/**
Finds the positions of all strings equal to a given string
in an array list of strings.
@param words an array list of strings
@param searchedWord the word to search for
@return an array list of all matching positions
*/
public static ArrayList<. . .> findAll(. . . words, . . . searchedWord)
{
. . .
}
}

Explanation / Answer


import java.util.ArrayList;

public class ArrayListUtil
{
/**
Finds the positions of all strings equal to a given string
in an array list of strings.
@param words an array list of strings
@param searchedWord the word to search for
@return an array list of all matching positions
*/
public static ArrayList<Integer> findAll(ArrayList<String> words, String searchedWord)
{
   ArrayList<Integer> pos = new ArrayList<>();
   int i = 0;
for(String temp:words){
   if(temp.equals(searchedWord))
       pos.add(i);
   i++;
}
  
return pos;
}

}
//------------------------------------------------------------------

Output:

[2, 5, 10, 14]
Expected: [2, 5, 10, 14]
[4, 9]
Expected: [4, 9]
[]
Expected: []

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