Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set all references of object to null

Tags:

java

reference

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 are a reference to bar) to null only with access to bar? If so, could somebody please explain how to do so.

like image 418
rodit Avatar asked Nov 08 '15 16:11

rodit


People also ask

How do you set all object values to null?

To set all values in an object to null , pass the object to the Object. keys() method to get an array of the object's keys and use the forEach() method to iterate over the array, setting each value to null . After the last iteration, the object will contain only null values.

Can you set a reference to null?

A reference isn't supposed to be null. The variable must be initialized to a non-null value. The variable can never be assigned the value null . The compiler issues a warning when code assigns a maybe-null expression to a variable that shouldn't be null.

Can you set an object to null?

In order to set object values to null, you need to get all the keys from the object and need to set null. You can use for loop or forEach() loop.

Can we assign null to object in Javascript?

Javascript. The null can not be assigned to undefined type variables: Javascript.


1 Answers

No, it is not possible in Java.

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

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

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

like image 158
Mateusz Korwel Avatar answered Sep 18 '22 20:09

Mateusz Korwel