0

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

kalki
  • 37
  • 1
  • 7
  • How do you call the method? From `main`? – XtremeBaumer Jul 15 '22 at 07:09
  • @XtremeBaumer yes, foo can be called from main – kalki Jul 15 '22 at 07:12
  • 2
    this is NOT about arrays and `ArrayList` - just about `static` and non-`static` || (a non-`static` method needs an instance to be called on, or be inside a method of an instance that serves as such - `main` is not such a method, it is a `static` one) - important concept of OO programming - you MUST learn about it – user16320675 Jul 15 '22 at 07:29
  • As said above, `main` is a static method, while `swap` is not - hence the error message – XtremeBaumer Jul 15 '22 at 07:33
  • 1
    Aside: you cannot pass *anything* by reference in Java. (But you can pass a reference by value.) I think you need to read about what "pass by reference" actually means. There is a good chance that is is NOT what you think it means! See https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference – Stephen C Jul 15 '22 at 07:47

1 Answers1

0

As the error messages says try turn swap methood into static.