2

我有一个名为Point如下的类:

public class Point {
    public int x;
    public int y;

    public Point(int X, int Y){
        x = X;
        y = Y;
    }

    public double Distance(Point p){
        return sqrt(((this.x - p.x) * (this.x - p.x)) + ((this.y - p.y) * (this.y - p.y)));
    }

    protected void finalize()
    {
        System.out.println( "One point has been destroyed.");
    } 
}

我有一个来自此类的对象,命名p如下:

Point p = new Point(50,50);

我想删除这个对象,我搜索了怎么做,我找到的唯一解决方案是:

p = null;

但是Point的finalize方法在我做完之后就不起作用了。我能做些什么?

4

8 回答 8

5

完成后p = null;,您的点的最后一个引用被删除,垃圾收集器现在收集该实例,因为没有对该实例的引用。如果调用System.gc();垃圾收集器,将回收未使用的对象并调用该对象的 finalize 方法。

    Point p = new Point(50,50);
    p = null;
    System.gc();

输出:One point has been destroyed.

于 2014-07-11T08:03:19.747 回答
4

您不能在 java 中删除对象,这是 GC (Garbage Collector) 的工作,它查找并删除未引用的实例变量。这意味着不再指向或引用的变量,这意味着它们现在无法被调用。因此,当您这样做时,您将 null 分配给持有对对象p = null;的引用的引用变量。Point因此,现在指向的 Point 对象是p可垃圾回收的。

同样根据javadoc for finalize()method,

Called by the garbage collector on an object when garbage collection 
determines that there are no more references to the object. 
A subclass overrides the finalize method
to dispose of system resources or to perform other cleanup.

但是不能保证调用finalize()方法,因为不能保证 GC 在特定时间(确定性时间)运行。

于 2014-07-11T07:57:42.543 回答
1

当没有指向该对象的剩余指针时,可以销毁该对象。

它被垃圾收集器随机删除。可以打电话System.gc(),但不推荐。系统应该是能够管理内存的系统。

于 2014-07-11T07:58:42.210 回答
1

实际上 p = null 只会使对象在java堆中丢失引用。但是,对象 P 仍然处于活动状态。如果您使用 System.gc() 您将能够清理所有活动对象,包括它在 java 堆中的引用。所以,我建议在执行 p = null 之后使用 System.gc()

于 2014-07-11T08:16:09.950 回答
0

在java中没有“删除对象”这样的东西。当垃圾收集器发现没有对它的引用时,它会自动删除对象。finalize()在对象从内存中永久删除之前,垃圾收集器也会自动调用该方法。您无法控制何时发生这种情况。

于 2014-07-11T07:55:57.023 回答
0

您不需要销毁对象,垃圾收集器会为您完成。

于 2014-07-11T07:56:31.223 回答
0

当不再引用的对象成为可声明的候选对象时,GC 回收对象。对于基本应用程序,无法确定 GC 是否在进程生命周期内运行。因此,这是一个测试理论的小例子:

public class Test {
    static class Sample {
        @Override
        protected void finalize() throws Throwable {
            System.out.print(this + " The END");    
        } 
    }
    public static void main(String...args) throws Exception {
        // Extra care 
        Runtime.getRuntime().runFinalization();
        Sample sample = new Sample(); sample = null; // Object no longer referenced
        System.gc(); // Ensures FULL GC before application exits
        Thread.sleep(1000); // Relax and see finalization out log
    }
}
于 2014-07-11T08:24:50.220 回答
0

如果没有方法调用点并且不是因为内存管理问题,则将其留给垃圾收集器或显式调用它。否则请提及为什么要删除它,以便建议其他方式。

于 2014-07-11T08:25:53.003 回答