Removing node in java

When we remove a node in java we just do

n.data=n.next.data;
n.next=n.next.next;

      

(To remove node n.next).

Does this mean the purpose of deletion or do we have some method of deleting a remote node (like free (n.next) in C)?

+3


source to share


4 answers


You cannot delete an object in Java, as such. You can only mark an object suitable for garbage collection by removing all references to its instance. The actual time that garbage collection will run and memory will be freed is determined by the JVM and cannot be explicitly controlled. In your example, if you remove the only reference to some Node, only then it will be eligible for GC.



+3


source


You can just say:

n.next = n.next.next

      



In java, this is enough.

0


source


In java, there is no need to explicitly delete java objects. The JVM automatically disposes of java objects using the garbage collector when there are no more references to the object. So if you don't use an object, besides, just null refer to it.

So your code is

n.data=n.next.data;
n.next=n.next.next;

      

implicitly removes (no access to the previous n.next object) the reference to the unneeded object.

0


source


You need to make sure there are no references to the "remote" node. There might be a bit of clarification for Kon's answer - you cannot delete an object, and when all references to it go out of scope, that object will be (eventually) garbage collected by the JVM. Otherwise, if you expect some references to stick, you should help the JVM by programmatically assigning it to null, or alternatively, as in your code below, reassign that reference to another object.

n.next=n.next.next 

      

So your code is fine if you know that n.next on the first line of your code is the only reference to the node to be removed, or all other references are local variables to the method and will go out of scope when the method returns.

0


source







All Articles