Find the positions of all strings equal to a given string in

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)
{
. . .
}
}

Solution

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<Integer> findAll(ArrayList<String> words, String searchedWord)
{
   ArrayList<Integer> list = new ArrayList<Integer>();
   for(int i=0; i< words.size();i++){
       if(words.get(i).equalsIgnoreCase(searchedWord)){
           list.add(i);
       }
   }
   return list;
}

}

Tester.java

import java.util.ArrayList;

public class Tester
{
public static void main(String[] args)
{
ArrayList<String> words = new ArrayList<String>();
words.add(\"how\");
words.add(\"much\");
words.add(\"wood\");
words.add(\"would\");
words.add(\"a\");
words.add(\"wood\");
words.add(\"chuck\");
words.add(\"chuck\");
words.add(\"if\");
words.add(\"a\");
words.add(\"wood\");
words.add(\"chuck\");
words.add(\"could\");
words.add(\"chuck\");
words.add(\"wood\");
System.out.println(ArrayListUtil.findAll(words, \"wood\"));
System.out.println(\"Expected: [2, 5, 10, 14]\");
System.out.println(ArrayListUtil.findAll(words, \"a\"));
System.out.println(\"Expected: [4, 9]\");
System.out.println(ArrayListUtil.findAll(words, \"the\"));
System.out.println(\"Expected: []\");
}
}

Output:

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

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 ma
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 ma

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site