Reputation: 41
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.
Upvotes: 1
Views: 4404
Reputation: 600
The Collections.swap(List, int, int) JDK 1.4+ method does just this. Here's an example:
Collections.swap(myList, 0, 1)
Upvotes: 1
Reputation: 1545
You need to use set instead of add.
if you use set it will replace the element in that position with the new element.
// arrayList.set(index i,String replaceElement);
so your swap function should look like this:
public class swap {
void swap(int x, int y, List <String> myList) {
String s = myList.get(x);
myList.set(x, myList.get(y));
myList.set(y, s);
System.out.println(myList);
} }
Upvotes: 0
Reputation: 3181
What your code does is:
So if you have a list with content ["A", "B", "C", "D", "E"]
, and you called swap(1, 3, list)
, following the pseudocode, you'd get:
s
becomes "B"["A", **"D"**, "B", "C", "D", "E"]
["A", "D", "B", **"B"**, "C", "D", "E"]
What you want to do is swap the values at x
and y
by SETTING them, not adding them:
void swap(int x, int y, List <String> myList) {
String s = myList.get(x);
myList.set(x, myList.get(y));
myList.set(y, s);
System.out.println(myList);
}
This will actually replace the values at index x
and y
with each other
Upvotes: 1
Reputation: 40328
Take a look at the ArrayList API, specifically the set() method. http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set(int,%20E)
public E set(int index, E element)
"Replaces the element at the specified position in this list with the specified element."
Give that method a shot instead of add(), probably as follows:
Basically, whenever you're stuck, it can't hurt to browse the API to see if any of the other methods might make the task a bit easier. None of us know the API completely by heart, and going back to that doc is a common thing for everyone. Well, almost everyone.
Upvotes: 1