-1

i want to swap between 2 bitmap, but i have a problem can not swap it

My code as below:

   private static void  swapBitmap(Bitmap c1, Bitmap c2) {
        Bitmap temp = c1;
        c1 = c2;
        c2 = temp;
    }

anyone can you guys help me this problem.Thanks you

Thang
  • 409
  • 1
  • 6
  • 17

1 Answers1

1

The short answer of why this doesn't work is because Java is "pass-by-value" and not "pass-by reference". If you want to know more about it I suggest reading the answers and comments here: Is Java "pass-by-reference" or "pass-by-value"?

What it basically means is that the parameter values you work with inside a function are different variables than the ones you passed. Note though that that they still point to the same object. So modifying any properties of it will also change it for the original reference. To illustrate take a look at this code:

public class Main
{
    public static void main(String[] args) {
        int i = 1;
        doSomething(i);
        System.out.println(i); //prints 1, can't reassign variables like this.

        A test = new A();
        test.i = 1;
        System.out.println(test.i); //prints 1
        doSomethingWithA(test);
        System.out.println(test.i); //prints 2, this does work because no reassignment is happening to test itself.

    }

    public static void doSomething(int i)
    {
        i = 2;
    }

    static class A {
        int i;
    }

    public static void doSomethingWithA(A a)
    {
        a.i = 2;
    }
}

So reassigning is not possible but changing properties of it is.

Ivo
  • 18,659
  • 2
  • 23
  • 35