Create an ArrayList of strings to store the names of celebrities and athletes. Add 5 names to the list. Process the list with a for loop and the get() method to display the names, one name per line. Pass the list to a void method. Inside the method, insert another name at Index 2 and remove the name at index 4. Use a Foreach loop to display the arraylist again, all names on one line separated by asterisks. After the method call in main, create an iterator for the arraylist and use it to display the list one more time.

Respuesta :

Answer:

// ArrayList class is imported

import java.util.ArrayList;

// Iterator class is imported

import java.util.Iterator;

// Main class is defined

class Main {

   // main method to begin program execution

   public static void main(String args[]) {

       // names ArrayList of String is defined

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

       // 5 names are added to the list

       names.add("John");

       names.add("Jonny");

       names.add("James");

       names.add("Joe");

       names.add("Jolly");

       // for loop to print the names inside the arraylist

       for(int index = 0; index <names.size(); index++){

         System.out.println(names.get(index));

       }

       

       // A blank line is printed

       System.out.println();

       // A newMethod is called with names as argument

       newMethod(names);

       // A blank line is printed

       System.out.println();

       // Instance of Iterator class is created on names

       Iterator<String> iter

           = names.iterator();

 

       // Displaying the names after iterating

       // through the list

       while (iter.hasNext()) {

           System.out.println(iter.next());

       }

   }

   // the newmethod is created here

   public static void newMethod(ArrayList<String> inputArray){

     // A new name is added at index 2

     inputArray.add(2, "Smith");

     // the name in index 4 is removed

     inputArray.remove(4);

     // for each is used to loop the list and print

     for (String name : inputArray) {

       System.out.println(name);

       }

   }

}

Explanation:

The code is well commented. An output image is attached.

Ver imagen ibnahmadbello