Develop a method to swap two elements with specified valid indexes I and j:
public void swap(int I, int j);
This is the method I have to use to swap two of the elements in an array list. The original list is: [a ==> b ==> c ==> d............] After calling swap(0, 2): [c ==> b ==> a ==> d............] This is what should print out for the output.
--------- First class-----
package it179.pa2;
import java.util.*;
public class MyArrayList {
private String list;
MyArrayList(String list) {
this.list = list;
}
MyArrayList() {
}
public void swap(int i, int j) {
int temp1;
temp1 = i;
i = j;
j = temp1;
}
@Override
public String toString() {
return list + "==>";
}
}
----- Second Class-----
package it179.pa2;
import java.util.*;
public class MyArrayListTest {
public static final void main (String[]args) {
MyArrayList my = new MyArrayList();
ArrayList<MyArrayList> al = new ArrayList<MyArrayList>();
al.add(new MyArrayList("A"));
al.add(new MyArrayList("B"));
al.add(new MyArrayList("C"));
al.add(new MyArrayList("D"));
al.add(new MyArrayList("E"));
al.add(new MyArrayList("F"));
System.out.print("The original list is: ");
for (MyArrayList tmp: al) {
System.out.print(tmp);
}// end of for
System.out.println("After calling swap(0,2): ");
System.out.print(al);
}
}
swapmethod is flipping the integer values of the parameters, e.g. if you callswap(1, 3), you'll initially havei = 1, j = 3, and at the end you'll havei = 3, j = 1. None of that touched thelist, so why would you expect the list to have changed? Of course, it's so much worse than that: 1) You don't even callswap. 2) Why doesMyArrayListhave a field namedlistof typeString? That's not list. 3) None of that has access toal, so how do you expect the actual list to be updated?