在java中删除类对象

我有一个名为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 - px) * (this.x - px)) + ((this.y - py) * (this.y - py))); } protected void finalize() { System.out.println( "One point has been destroyed."); } } 

我有一个名为p类中的对象,如下所示:

 Point p = new Point(50,50); 

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

 p = null; 

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

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

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

输出: One point has been destroyed.

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

另外根据javadoc for 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()方法,因为GC不能保证在特定时间(确定性时间)运行。

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

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

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

你不需要销毁对象,垃圾收集器会为你做。

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

当不再引用的对象成为可索赔的候选对象时,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 } } 

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