Set all object references to null

In Java, how would I do the following:

Foo bar = new Foo(); Foo a = bar; Foo b = bar; bar = null;//will only set bar to null. want to set value of bar to null rather than the reference to null. 

Is it possible to set the variables bar , a and b (all references to bar ) to null only with access to the bar? If so, can someone explain how to do this.

+7
java reference
source share
3 answers

This is not possible in Java. You cannot set the link a and b null using bar .

The reason is Java pass by value not pass by reference .

+3
source share

No, this is not possible in Java.

I will explain a little what happened in your code. Here Foo bar = new Foo(); You created a Foo object and put a reference to the bar variable.

Here Foo a = bar; and Foo b = bar; you put a reference to variables a and b . So now you have one object and three variables pointing to it.

Here bar = null; you clear the bar variable. Thus, you have two variables ( a and b ) pointing to the object and one variable ( bar ) without reference.

+5
source share

There is no destructor in Java, for example, in C:

  • destructor-for-java

If you knew you wanted to set multiple objects to null, then you are likely to use the Foo array, rather than declaring them as separate objects. Then use loops for consturctor calls, initialization / initialization.

 Foo bar = new Foo(); Foo array[2] for (int i=0; i<array.length; i++) { array[i] = bar; } 

Then you can use a loop at the end

 for (int i=0; i<array.length; i++) { array[i] = null; } 

This is the strategy you want to use for Data Structures because you can process any number of objects, for recursion, etc.

+2
source share

All Articles