D. Hoffman D. Hoffman - 27 days ago 11
Java Question

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

I'm just assuming that a and b are valid integers based on the size of the ArrayList for simplicity sake. I feel however that I am missing something. I set up the ArrayList properly but something still isn't making sense to me. Does anyone see anything? Thanks in advance.

Answer Source

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);