Deleting an object in java?

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

delete follower1;

didn't work.

EDIT:

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;
}
}
451425 次浏览

Java has a Garbage Collector, it will delete the object for you if no reference is held to it anymore.

If you want help an object go away, set its reference to null.

String x = "sadfasdfasd";
// do stuff
x = null;

将引用设置为 null 将使对象更有可能被垃圾收集,只要没有对该对象的其他引用。

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

例子一:

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

例二:

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 ()来调用垃圾收集器

你不需要删除 java 中的对象。当没有对对象的引用时,垃圾收集器将自动收集该对象。

你的 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仍然引用该对象,因此还不能收集它。

//Just use a List
//create the list
public final List<Object> myObjects;


//instantiate the list
myObjects = new ArrayList<Object>();


//add objects to the list
Object object = myObject;
myObjects.add(object);


//remove the object calling this method if you have more than 1 objects still works with 1
//object too.


private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}

可以使用 null删除引用。

假设你有 A班:

A a = new A();
a=null;

最后一个语句将删除对象 a的引用,该对象将被 JVM“垃圾收集”。 这是最简单的方法之一。