Question

Here is my democlass where i am trying to implement the switching mechanism and trying to figure out how the object references are passed while executing methods: Here is my main demo class:

package referenceOrValue;

import java.util.ArrayList;

public class DemoFoo {
public static void main(String[] args) {
    ArrayList<String> demoArray = new ArrayList<>();
    ArrayList<String> arrayList = new ArrayList<>();

    arrayList.add("a");
    arrayList.add("b");
    arrayList.add("c");
    demoArray.add("d");
    demoArray.add("e");
    demoArray.add("f");


    System.out.println("The arraylist  is " + arrayList);
    System.out.println("The demo array is " + demoArray);
    Foo foo = new Foo();    


    //foo.setNull(arrayList);
    foo.switching(arrayList, demoArray);
    System.out.println("The arraylist  after switch " + arrayList);
     System.out.println("The demo array after switch " + demoArray);




}

}

now there is a foo class like this whose sole function is to swap the values in the arraylist:

package referenceOrValue;

import java.util.ArrayList;

public class Foo {

public void switching (ArrayList<String> a, ArrayList<String> b){

    ArrayList<String> temp=null;
temp=a;
a=b;
b=temp;
System.out.println("The arraylist  inside switch " + a);
System.out.println("The demo array inside switch " + b);
}
}

now the main problem is the output:-(

The arraylist  is [a, b, c]
The demo array is [d, e, f]
The arraylist  inside switch [d, e, f]
The demo array inside switch [a, b, c]
The arraylist  after switch [a, b, c]
The demo array after switch [d, e, f]

According to my knowledge the this switching should have executed properly but result is bit surprising for me as inside the switching method i am not creating new objects as:

a= new ArrayList<>();

so "a" is still referring to the [a,b,c] and during the switching operation values are changed in the method as shown in output, but the main class has unchanged object. Please help!!

Was it helpful?

Solution

Directly after passing in the array lists into the method ...

  1. ... the parameter a is referencing the same array list as the variable arrayList from main method
  2. ... the parameter b is referencing the same array list as the variable demoArray from main method.

But before printing out the contents you switch the references! So at the point where you print the contents ...

  1. ... the parameter a is referencing the same array list as the variable demoArray from main method
  2. ... the parameter b is referencing the same array list as the variable arrayList from main method.

And as Java always passes by value, the variables (which just hold references) in the main method are untouched. So they print out the same content as before.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top