JAVA

Write a method that takes 2 parameters: an ArrayList list, and an int numRepeats representing the number of times to repeat each element in the array.


Return a new ArrayList with each element repeated numRepeats times.


For example, if we had an ArrayList list with the values ["hello", "world"]:


repeatElements(list, 3)

Should return a new ArrayList with the elements:


["hello", "hello", "hello", "world", "world", "world"]


public ArrayList repeatElements(ArrayList list, int numRepeats)

{


}

Respuesta :

Answer:

Explanation:

The following Java code creates the repeatElements method as requested and uses the test case shown in the question to test the method. The output can be seen in the attached picture below.

import java.util.ArrayList;

class Brainly {

   public static void main(String[] args) {

       ArrayList list = new ArrayList();

       list.add("Hello");

       list.add("World");

       System.out.println(repeatElements(list, 3));

   }

   public static ArrayList repeatElements(ArrayList list, int numRepeats) {

       ArrayList newList = new ArrayList();

       for (Object x:list) {

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

               newList.add(x);

           }

       }  

       return newList;

   }

}

Ver imagen sandlee09
RELAXING NOICE
Relax