120

I want to delete an object I created, (e.g. an oval that follows you), but how would I do this? I ran the statement:

delete follower1;

but it didn't work.

Background:

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 also have enemy.class, which is the oval following the player. I also have entity.class, which is the player you can control. And if the player intersects with the follower (the enemy), I want my player object to get deleted. Currently, the way I'm doing it is:

public void checkCollisions(){
    if(player.getBounds().intersects(follower1.getBounds())){
        Follower1Alive = false;
        player.health = player.health - 10;
     }
 }
6
  • 1
    can you provide a little more context? Commented Apr 22, 2011 at 16:26
  • 2
    There is no deletion of objects in Java. But you normally don't need to: what you need is to make sure there is nothing shown at screen anymore (if this is what "following you" is doing). Commented Apr 22, 2011 at 16:32
  • Perhaps you want to try and force garbage collector to remove an object? there is a question about it here already. Or perhaps you trying something else? you can try reading a bit about the garbage collector here or here If its still no help, you will need to be more specific. Commented Apr 22, 2011 at 16:35
  • possible duplicate of Force explicit deletion of a Java object Commented Jan 29, 2015 at 11:06
  • If you really really really want to handle object allocations manually, use JNI: create a C/C++ lib which is used from Java code but does everything (create, delete, etc.) on it's own - but inside your lib you have C/C++ code, no Java. I've not seen any way to delete a Java object manually. If your profiler tells you that there are problems, these problems often base on "forgotten" references to objects. In your case there does not seem to be a problem anywhere. Commented Jan 15, 2016 at 10:12

7 Answers 7

212

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).

Example 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

Example 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.

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

Sign up to request clarification or add additional context in comments.

5 Comments

Having to manually call System.gc() is generally not a good idea, since it may actually be ignored by the JVM.
Not a good idea, but you can also call similar to System.. Runtime.getRuntime().gc(). More Info:he garbage collection routines that Java provides are members of the Runtime class. The Runtime class is a special class that has a single object (a Singleton) for each main program. The Runtime object provides a mechanism for communicating directly with the virtual machine. To get the Runtime instance, you can use the method Runtime.getRuntime(), which returns the Singleton.
Is null assignment a definite sign to the GC that this object is to be Garbaged Cleaned in the next GC invocation?* Assigning null to collection objects (Lists, Arrays) marks them for cleaning? stackoverflow.com/questions/449409/…
There is no guarantee that the garbage collector will ever run, or that, if it does, it will collect (not 'delete') any specific object.
The point with the Example 1 is that if for some reason you need that object again it will throw a NPE.
83

Your C++ is showing.

There is no delete in java, and all objects are created on the heap. The JVM has a garbage collector that relies on reference counts.

Once there are no more references to an object, it becomes available for collection by the garbage collector.

myObject = null may not do it; for example:

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

All this does is set the reference myObject to null, it does not affect the object myObject once pointed to except to simply decrement the reference count by 1. Since myOtherObject still refers to that object, it is not yet available to be collected.

3 Comments

"The JVM has a garbage collector that relies on reference counts." -> that's a very simplified explanation. It checks whether objects are reachable from a specific "root"
The JVM has a garbage collector that specifically does not rely on reference counts. It relies on reachability. If it relied on reference counts it could never collect cycles, and it does.
is there a way to invalidate the identifier after setting it to null? I'm not suggesting that it would be used for another pointer to a different type or something (it's generally not wise to have 2 identifiers in the same scope used for different things. Why not 2 different names?); I just might want to compiler to yell at me me if I try to use that identifier after I've set it to null.
15

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

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

Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.

3 Comments

Whenever I do that, when my object intersects, my whole game will freeze, and it will not delete the object.
Because you're probably throwing an uncaught null pointer exception. More context would certainly help us guide you through this.
If you really need them to go away, then that would do it eventually.
4

You don't need to delete objects in java. When there is no reference to an object, it will be collected by the garbage collector automatically.

1 Comment

@RuchirBaronia No. They are still referenced by your AppCompatActivity, but if the AppCompatActivity is not referenced anymore, they will be deleted.
1

You can remove the reference using null.

Let's say You have class A:

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

last statement will remove the reference of the object a and that object will be "garbage collected" by JVM. It is one of the easiest ways to do this.

Comments

-2

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

3 Comments

in the least expected moment
s/delete/leak/g
The Java garbage collector is notorious for locking up the main thread for up to half a second if there are a lot of objects to clean. Minecraft is an infamous example of this very issue. So in cases like that, there is a good reason why you may not want to use the garbage collector.
-8
//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);
}
}

2 Comments

The reason this answer is incorrect is because it only removes a reference to the Object, and not the actual object itself.
The reason why this answer is incorrect because it shows how you can remove an object from a list - this was not the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.