For a Java Array, we can swap the elements present at indexes first
and second
like this:
public void func(int[] array) {
int first = 1;
int second = 2;
swap(array, first, second);
}
public void swap(int[] array, int first, int second) {
int tmp = array[first];
array[first] = array[second];
array[second] = tmp;
}
How to do the same thing if array is an ArrayList?
Here is what I tried:
public void swap(ArrayList<Integer> array, int first, int second){
int tmp = array.get(first);
array.set(first, array.get(second));
array.set(second, tmp);
}
but it throws the following error:
error: non-static method swap(ArrayList,int,int) cannot be referenced from a static context swap(A, i, j);