I've been trying to figure out how to swap items in an arraylist; so first I created an arraylist using this code:
import java.util.ArrayList;
import java.util.List;
public class ListADT {
public static void main (String[] args){
List <String> myList = new ArrayList<String>(); {
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");
System.out.println(myList);}}}
This returns [A,B,C,D,E] on the console.
Then I opened up another class and used this code I found online and tried to make modifications to get it to work, but it has not been working.
import java.util.List;
public class swap {
//precondition: x and y are >= 0 and < mylist.size()
//precondition: mylist is not null
void swap(int x, int y, List <String> myList) {
String s = myList.get(x);
myList.add(x, myList.get(y));
myList.add(y, s);
System.out.println(myList);
} }
If I try to replace x and y with position numbers of the elements in the list, then that just causes a host of new problems. As you can probably tell, I'm a beginner to this and any help would be appreciated.
You need to use set instead of add.
if you use set it will replace the element in that position with the new element.
so your swap function should look like this: