120

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;
    }
}
6
  • 1
    can you provide a little more context? 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). 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.
    – Fawix
    Apr 22, 2011 at 16:35
  • possible duplicate of Force explicit deletion of a Java object 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.
    – Johannes
    Jan 15, 2016 at 10:12

7 Answers 7

213

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

6
  • 30
    Having to manually call System.gc() is generally not a good idea, since it may actually be ignored by the JVM. Jun 22, 2013 at 22:51
  • 3
    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.
    – Timo
    Nov 12, 2013 at 13:54
  • 1
    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/… Mar 22, 2015 at 17:21
  • So I should make all of my textviews and imagebuttons null in the onPause? Jan 10, 2016 at 0:44
  • There is no guarantee that the garbage collector will ever run, or that, if it does, it will collect (not 'delete') any specific object.
    – user207421
    Jan 20, 2017 at 6:11
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.

4
  • So I should make all of my textviews and imagebuttons null in the onPause? Jan 10, 2016 at 0:44
  • 11
    "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"
    – Johannes
    Jan 15, 2016 at 10:04
  • 5
    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.
    – user207421
    Jan 20, 2017 at 6:12
  • 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. Apr 10, 2021 at 17:07
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.

4
  • Whenever I do that, when my object intersects, my whole game will freeze, and it will not delete the object.
    – Stan
    Apr 22, 2011 at 17:00
  • 1
    Because you're probably throwing an uncaught null pointer exception. More context would certainly help us guide you through this. Apr 22, 2011 at 17:09
  • So I should make all of my textviews and imagebuttons null in the onPause? Jan 10, 2016 at 0:45
  • If you really need them to go away, then that would do it eventually. Jan 10, 2016 at 1:53
3

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.

2
  • So I should make all of my textviews and imagebuttons null in the onPause? Jan 10, 2016 at 0:45
  • @RuchirBaronia No. They are still referenced by your AppCompatActivity, but if the AppCompatActivity is not referenced anymore, they will be deleted.
    – Cactusroot
    Jul 7, 2021 at 11:17
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.

1
  • So I should make all of my textviews and imagebuttons null in the onPause? Jan 10, 2016 at 0:45
-2

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

3
  • 43
    in the least expected moment
    – matcheek
    Apr 22, 2011 at 16:26
  • 3
    s/delete/leak/g Oct 16, 2016 at 20:55
  • 2
    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.
    – AyesC
    Jan 22, 2022 at 3:17
-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
  • 2
    The reason this answer is incorrect is because it only removes a reference to the Object, and not the actual object itself.
    – Ben Morris
    Aug 25, 2016 at 18:38
  • 2
    The reason why this answer is incorrect because it shows how you can remove an object from a list - this was not the question.
    – phil
    Jan 26, 2017 at 7:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.