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;
    }
}
Daniel Causebrook
  • 469
  • 1
  • 8
  • 20
Stan
  • 3,659
  • 14
  • 35
  • 42
  • 1
    can you provide a little more context? – Joseph Weissman Apr 22 '11 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). – Paŭlo Ebermann Apr 22 '11 at 16:32
  • possible duplicate of [Force explicit deletion of a Java object](http://stackoverflow.com/questions/2178028/force-explicit-deletion-of-a-java-object) – Ciro Santilli OurBigBook.com Jan 29 '15 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 '16 at 10:12
  • Perhaps you want to try and force garbage collector to remove an object? there is a question about it [here](http://stackoverflow.com/questions/2178028/force-explicit-deletion-of-a-java-object) already. Or perhaps you trying something else? you can try reading a bit about the garbage collector [here](http://www.javaworld.com/javaworld/javatips/jw-javatip79.html) or [here](http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html) If its still no help, you will need to be more specific. – Fawix Apr 22 '11 at 16:35
  • Um, what would happened if I replace/assigning it with new reference? `Object obj1 = new Object()` to `obj1 = new Object()`, is the previous ref/obj is deleted instantly after it assign to a new one? – Liveon Phoenix Nov 20 '21 at 12:38

7 Answers7

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

Pablo
  • 77
  • 1
  • 7
MByD
  • 135,866
  • 28
  • 264
  • 277
  • 30
    Having to manually call `System.gc()` is generally [not a good idea](http://stackoverflow.com/questions/2414105/why-is-it-a-bad-practice-to-call-system-gc), since it may actually be ignored by the JVM. – christiandeange Jun 22 '13 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 '13 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? http://stackoverflow.com/questions/449409/does-assigning-objects-to-null-in-java-impact-garbage-collection – George Daramouskas Mar 22 '15 at 17:21
  • So I should make all of my textviews and imagebuttons null in the `onPause`? – Ruchir Baronia Jan 10 '16 at 00: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 '17 at 06:11
  • The point with the Example 1 is that if for some reason you need that object again it will throw a NPE. – karlihnos Mar 23 '18 at 08:56
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.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • So I should make all of my textviews and imagebuttons null in the `onPause`? – Ruchir Baronia Jan 10 '16 at 00: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"](http://stackoverflow.com/a/1910203/2714781) – Johannes Jan 15 '16 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 '17 at 06: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. – Twisted on STRIKE at1687989253 Apr 10 '21 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.

John Percival Hackworth
  • 11,395
  • 2
  • 29
  • 38
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.

fmucar
  • 14,361
  • 2
  • 45
  • 50
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.

jiaweizhang
  • 809
  • 1
  • 11
  • 28
Lakhan
  • 73
  • 1
  • 8
-2

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

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
Jake Kalstad
  • 2,045
  • 14
  • 20
  • 43
    in the least expected moment – matcheek Apr 22 '11 at 16:26
  • 3
    s/delete/leak/g – Mark K Cowan Oct 16 '16 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 '22 at 03: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
    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 '16 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 '17 at 07:04