在java中删除对象? [英] Deleting an object in java?

查看:37
本文介绍了在java中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除我创建的对象(跟随您的椭圆),但是我该怎么做?

I want to delete an object I created, (a oval which follows you), but how would I do this?

delete follower1;

没有用.

好的,我会提供更多背景信息.我正在制作一个小游戏,里面有一个你可以控制的椭圆形,还有一个跟随你的椭圆形.现在我有一个名为:DrawPanel.class 的文件,这个类在屏幕上绘制所有东西,并处理碰撞、声音等.我有一个enemy.class,它是跟随玩家的椭圆形.我有一个entity.class,这是你可以控制的播放器.如果玩家与跟随者相交,我希望我的玩家对象被删除.我的做法是:

Okay, I'll give some more context. I'm making a small game with a oval you can control, and a oval which follows you. Now I've got files named: DrawPanel.class, this class draws everything on the screen, and handles collisions, sounds, etc. I got an enemy.class, which is the oval following the player. I got an entity.class, which is the player you can control. And if the player intersects with the follower, I want my player object to get deleted. The way I'm doing it:

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

推荐答案

您应该通过分配 null 或保留声明它的块来删除对它的引用.之后,它会被垃圾收集器自动删除(不是立即删除,而是最终删除).

You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).

示例 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.

不是您当前正在寻找的东西,但仅供参考:您可以通过调用来调用垃圾收集器 System.gc()

Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()

这篇关于在java中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆