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

查看:92
本文介绍了删除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 he 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天全站免登陆