在java中删除类对象

时间:2014-07-11 07:51:59

标签: java class object-destruction

我有一个名为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方法不起作用。我该怎么办?

8 个答案:

答案 0 :(得分:4)

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

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

输出:One point has been destroyed.

答案 1 :(得分:3)

你无法删除java中的对象,这就是GC(垃圾收集器)的工作,它可以找到和删除未引用的实例变量。这意味着不再指向或引用的变量,这意味着它们现在无法被调用。因此,当您执行此操作p = null;时,您将为引用Point对象的引用变量分配null。因此,现在由p指向的Point对象是垃圾收集的。

同样根据finalize() 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()
  

但无法保证调用{{1}}方法,因为GC无法保证在特定时间(确定时间)运行。

答案 2 :(得分:1)

当strre不是指向此对象的剩余指针时,对象可以被删除。

随机时间被垃圾收集器删除。 您可以致电System.gc(),但不建议这样做。系统应该是能够管理内存的系统。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

实际上p = null只会使对象在java堆中丢失引用。但是,对象P仍然有效。如果使用System.gc(),您将能够清除所有活动对象,包括它在Java堆中的引用。因此,我建议在执行p = null

后使用System.gc()

答案 6 :(得分: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
    }
}

答案 7 :(得分:0)

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