Destroy objects in Java
                                        
                    •
                    Java                                    
                If I set a null object, will Java destroy the original object?
For example:
Foo f = new Foo(); // ... Foo b = f;
If I set B to null now, will f also become empty? What is the common name for this behavior?
Solution
no All setting B to null removes the reference of the object from B F still references the object If f is also set to null, the object will have no outstanding references and will eventually be garbage collected
Let's throw some ASCII art here:
First, let's do this:
Foo f = new Foo();
And get this in memory:
+------------+
|     f      |
+------------+     +-----------------------+
| (Ref #123) |---->|       Foo #123        |
+------------+     +-----------------------+
                   | (data for the object) |
                   +-----------------------+
(obviously, #123 just to give an idea that REF does have some specific values; we've never seen the actual value, but the JVM does.)
Then, if we do this:
Foo b = f;
We have:
+------------+
|     f      |
+------------+
| (Ref #123) |--+
+------------+  |
                |
                |  +-----------------------+
                +->|       Foo #123        |
+------------+  |  +-----------------------+
|     b      |  |  | (data for the object) |
+------------+  |  +-----------------------+
| (Ref #123) |--+
+------------+ 
If we do
b = null;
We have:
+------------+
|     f      |
+------------+     +-----------------------+
| (Ref #123) |---->|       Foo #123        |
+------------+     +-----------------------+
                   | (data for the object) |
+------------+     +-----------------------+
|     b      |
+------------+
| null       |
+------------+ 
As you can see, F and the object itself are not affected
                            The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
                        
                                            
                        THE END
                    
                    
                    
                                                        二维码
                        
                        
                                                
                        