164k views
1 vote
Write a method doubleList that takes an ArrayList of Strings as a parameter and that replaces every string with two of that string. For example, if the list stores the values {"how", "are", "you?"} before the method is called, it should store the values {"how", "how", "are", "are", "you?", "you?"} after the method finishes executing.

User Cem U
by
6.5k points

1 Answer

6 votes

Answer:

// Method to double the content in a list

// Method receives an arraylist as parameter

public static void doubleList(ArrayList<String> stringlist) {

// Create a new array list to hold the new content

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

// Create a loop that cycle through the string list

// For every cycle, get the current content of the list

// and add it twice to the new list

for (int i = 0; i < stringlist.size(); i++) {

newList.add(stringlist.get(i));

newList.add(stringlist.get(i));

}

// Copy the content of the new list back to the string list

stringlist = newList;

// Display the result

System.out.println(stringlist);

}

Step-by-step explanation:

Please go through the comments in the code for better understanding and readability.

Hope this helps!

User Dr Mido
by
6.3k points