问题描述
我有一个名为 Point
的课程如下:
I have a class named Point
as below:
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.");
}
}
我有一个名为<$ c的类中的对象$ c> p 如下:
Point p = new Point(50,50);
我想删除这个对象,我搜索了怎么做,我找到的唯一解决方案是:
I want to delete this object, I searched how to do it, the only solution I found was:
p = null;
但是在我做完之后,Point的finalize方法不起作用。我该怎么办?
But the finalize method of Point didn't work after I did it. What can I do?
推荐答案
执行 p = null;
您的点的最后一个引用被删除,垃圾收集器现在收集实例,因为没有对此实例的引用。如果你调用 System.gc();
,垃圾回收器将回收未使用的对象并调用这个对象的finalize方法。
After you do p = null;
the last reference of your point is deleted and the garbage collector collects the instance now because there is no reference to this instance. If you call System.gc();
the garbage collector will recycle unused objects and invoke the finalize methods of this objects.
Point p = new Point(50,50);
p = null;
System.gc();
输出:一个点已被销毁。
这篇关于在java中删除类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!