user8570855
user8570855

Reputation:

Swapping items in ArrayList

I'm trying to create a method that swaps two items in an ArrayList. As an example I'm trying to make it so that oneList = ["dog", "cat", "mouse", "panda"] and then you do swap(1, 2, oneList) it will end up being ["dog", "mouse", "cat", "panda"]

void swap(int a, int b, ArrayList<String> oneList)
{
    oneList.set(a, oneList.get(b)) //puts whatever is in position b into position a
}

Upvotes: 2

Views: 4188

Answers (3)

Naman
Naman

Reputation: 31888

You can change to either using :

String temp = oneList.get(a); 
oneList.set(a, oneList.get(b));
oneList.set(b,temp);

Or use Collections built-in swap method

void swap(int a, int b, ArrayList<String> oneList) {
    // do some bounds check
    Collections.swap(oneList, a, b);
}

Upvotes: 4

Elliott Frisch
Elliott Frisch

Reputation: 201447

As the other answers have pointed out, you are only updating the first value in the list (you need to save it first, and then set the second one). Also, you could make the method generic on any type of List (please program to the interface). Like,

<T> void swap(int a, int b, List<T> oneList) {
    T t = oneList.get(a);
    oneList.set(a, oneList.get(b));
    oneList.set(b, t);
}

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521279

Use a temporary variable to make the swap possible:

void swap(int a, int b, ArrayList<String> oneList) {
    // you might also want to check that both a and b fall within the bounds of the list
    String temp = oneList.get(b);
    oneList.set(b, oneList.get(a));
    oneList.set(a, temp);
}

Upvotes: 1

Related Questions