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);
}
}
}
Step-by-step explanation:
The code is well commented. An output image is attached.