Answer:
Here is the JAVA program:
private static void mirror(ArrayList<String> list) { // method mirror that accepts ArrayList of Strings as a parameter
for (int i = list.size() - 1; i >= 0; i--) {//iterates through the array list
list.add(list.get(i)); } //produces a mirrored copy of the list
System.out.println(list); } ///prints the mirrored copy of list
Step-by-step explanation:
This is the complete program:
import java.util.ArrayList; //to use dynamic arrays
public class MirroredArraylist{
private static void mirror(ArrayList<String> list) { //method to produce mirrored copy of the list
for (int i = list.size() - 1; i >= 0; i--) { /
list.add(list.get(i)); }
System.out.println(list); }
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();//creates a String type array list
//adds values to the Arraylist i.e list
list.add("a"); .
list.add("b");
list.add("c");
mirror(list); }} //calss mirror method passing list to it
The method works as follows:
For loop variable i is initialized to the list.size() - 1 which means 1 less than the size of the ArrayList i.e list. For example the list contains the following values ["a", "b", "c"]. So
i = list.size() - 1
= 3-1
i = 2
so i is set to the last element/value of list i.e. "c"
Then the for loop checks if the value of i is greater than or equals to 0 which is true because i = 2
So the program control enters the body of the for loop
list.add(list.get(i)); This statement has two methods; add() and get()
add() method is used to add the value/element to the ArrayList, list.
get() method is used to get the element/value in list at i-th index
So the element at i=2 means element at 2nd index is "c"
Hence value "c" is added to the list.
Then the value of i is decremented to 1. So i=1
At next iteration
i is set to the second last element/value of list i.e. "b"
Then the for loop checks if the value of i is greater than or equals to 0 which is true because i = 1
So the program control enters the body of the for loop and gets the value of list i.e "b" and adds it to the list. Next the value of "a" is get and added to the list. So the list becomes:
["c", "b", "a"]
In the main() method
list.add("a"); .
list.add("b");
list.add("c");
The above three statements adds the values to list that are "a", "b" and "c". So the list becomes:
["a", "b", "c"]
Next statement mirror(list); calls the method mirror which returns the mirrored copy of the list. So the output is:
["a", "b", "c", "c", "b", "a"].
The screen shot of the program along with its output is attached.