简体   繁体   English

Java中对象的引用

[英]Object's references in Java

I'm have one question. 我有一个问题。

I have class Node 我有班级Node

public class Node {
    public final Key   KEY;
    public final Value VALUE;
    //Other fields and methods.
}

Method add 方法add

public void add(Key key, Value value) {
this.key   = key;
this.value = value;
//Other code
}

And this code: 这段代码:

//something here...
private Node node = new Node();
//Some code
add(node.KEY, node.VALUE);
node = null;

Is there node object will be utilized by garbage collector exclusive KEY and VALUE fields or node object with all another fields will be saved in memory? 是否有node对象将由垃圾收集器使用独占的KEYVALUE字段或node对象与所有其他字段将被保存在内存中?

KEY and VALUE will still have a reference in your program so they will not be garbage collected. KEYVALUE仍会在您的程序中有一个引用,因此它们不会被垃圾回收。 But since node has no more references in your program, it is now a candidate for a garbage collection. 但由于node在您的程序中没有更多引用,因此它现在是垃圾收集的候选者。

To make it clear. 说清楚。 node and its fields, excluding KEY and VALUE will be candidates for GC (assuming you didn't assign any other fields to an object that is still present and referred in your program) node及其字段( KEYVALUE除外)将成为GC的候选者(假设您没有将任何其他字段分配给仍存在并在您的程序中引用的对象)

Basically if a object has a reference regardless of whether it is a strong reference or a weak reference it will not get garbage collected. 基本上,如果一个对象具有引用,无论它是强引用还是弱引用,它都不会被垃圾收集。 The only way to get these objects garbage collected is to null the object at any time. 获取这些对象垃圾的唯一方法是随时使对象为空。

public class Node {
    public final Key   KEY=null;
    public final Value VALUE=null;
    //Other fields and methods.
}

Just make sure they get initialized before being called. 只需确保在被调用之前初始化它们。

As far as node is concerned because you set it null in the last line it will get garbaged collected. 就节点而言,因为你在最后一行将它设置为null,它将被收集。 Setting an object null removes reference therefor it is a null object and is garbage collected nothing is in the memory. 设置一个对象null会删除它的引用,因此它是一个空对象,并且是垃圾收集,内存中没有任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM