Search code examples
javaarraylistindexingswap

how to swap a string from one index to a different index?


This is my code so far I am not sure how to take the indices of a list [fish, chips, sauce, plate] and put chips at index plate is.

class Names{
      ArrayList<String> list;

public Names()
{
    list = new ArrayList<String>();
}

/**    precondition:    p and q represent indexes of existing elements in the list array.
  *      postcondition:  the elements, represented by p and q, have swapped locations.
      */
public void swapNames(int p, int q){      
      temp = p;
      p = q;
      q = temp;
   }
}

Solution

  • If p and q are valid indexes in the given array list, ArrayList's methods get(int i) and set(int i, E obj) can be used to efficiently swap the elements:

    public void swapNames(int p, int q) {
        String temp = list.get(p);
        list.set(p, list.get(q));
        list.set(q, temp);
       }
    }