如何从方法内删除对象?

14 浏览
0 Comments

如何从方法内删除对象?

我想删除我创建的一个物体(一个跟随你的椭圆形),但我该如何做到这一点?

delete follower1;

不起作用。

编辑:

好吧,我将提供更多的上下文。我正在制作一个小游戏,其中有一个可以控制的椭圆形和一个跟随你的椭圆形。现在我有一个名为DrawPanel.class的文件,这个类绘制屏幕上的所有内容,并处理碰撞、声音等等。我有一个敌人.class,这是跟随玩家的椭圆形体。我有一个entity.class,这是你可以控制的玩家。如果玩家与跟随者相交,我希望我的玩家对象被删除。我正在这样做:

    public void checkCollisions(){
    if(player.getBounds().intersects(follower1.getBounds())){
        Follower1Alive = false;
        player.health = player.health - 10;
    }
}

admin 更改状态以发布 2023年5月23日
0
0 Comments

你的C++表现出来了。

Java中没有delete,所有对象都被创建在堆中。JVM有一个垃圾回收器,依赖于引用计数。

一旦一个对象没有更多的引用,它就变得可以被垃圾回收器回收。

myObject = null可能不起作用,例如:

Foo myObject = new Foo(); // 1 reference
Foo myOtherObject = myObject; // 2 references
myObject = null; // 1 reference

这只是将引用myObject设置为null,它不会影响指向的对象myObject,只是简单地将引用计数减1。因为myOtherObject仍然指向该对象,所以它还不能被回收。

0
0 Comments

您应该通过将其赋值为null或离开声明块来删除对它的引用。在此之后,它将自动由垃圾回收器删除(不是立即,而是最终)。

示例1:

Object a = new Object();
a = null; // after this, if there is no reference to the object,
          // it will be deleted by the garbage collector

示例2:

if (something) {
    Object o = new Object(); 
} // as you leave the block, the reference is deleted.
  // Later on, the garbage collector will delete the object itself.

不是您目前正在查找的内容,但FYI:您可以使用调用 System.gc() 调用垃圾收集器

0