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

Write a method manyStrings that takes an ArrayList of Strings and an integer n a

ID: 3642960 • Letter: W

Question

Write a method manyStrings that takes an ArrayList of Strings and an integer n as parameters and that replaces every String in the original list with n of that String. For example, suppose that an ArrayList called "list" contains the following values:
("squid", "octopus")
And you make the following call:
manyStrings(list, 2);
Then list should store the following values after the call:
("squid", "squid", "octopus", "octopus")
As another example, suppose that list contains the following:
("a", "a", "b", "c")
and you make the following call:
manyStrings(list, 3);
Then list should store the following values after the call:
("a", "a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c")
You may assume that the ArrayList you are passed contains only Strings and that the integer n is greater than 0.

Explanation / Answer

public static ArrayList<String> manyStrings(ArrayList<String> list, int n) {

              ArrayList<String> newList = new ArrayList<String>();

              for(String s: list) {

                     for(int i = 0; i < n; ++i) {

                           newList.add(s);

                     }

              }

              return newList;

}

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