QuizCure
Find Available Solution Here!

Java Delete object

Deepak Apr 26, 2024

Before we move any further, we must first understand the object generation process and related mechanisms:

What happens once an object is created?

  • Newly formed objects take memory space in the heap.
  • Stack space is used to keep references to newly formed objects.

Therefore, certain memory is allocated for a new object in the heap space and stack space contains an address that points to the object that resides in the heap.

Let's quickly understand how garbage collectors work in Java. The heap's unreferenced objects are garbage, and they must be removed. A garbage collector frees the memory that was previously occupied by unreferenced/unused objects. The GC (automated process) is in place to provide better memory management, which results in better CPU utilization.

We will not go into depth regarding garbage collectors, but we do recommend that you learn about them, particularly if you are a newbie.

Let's get started on the current topic of Java delete object and other related questions with the following step-by-step definition. Let's get started.

In Java, how do you delete objects?

Garbage collectors destroy unreferenced objects to free up unused object-occupied memory, as we learned before.

To delete an object, we can set the object reference to null. However, this does not imply that the waste will be collected right away.

Also, Please note It is not generally required to delete objects. The garbage collector automatically remove the object which does not have any reference

Example:

public class Employee {

    private String name;

    private int id;


    public Employee(String name, int employeeID) {
        this.name = name;
        this.id = employeeID;    
    }

    public static void main(String[] args) {

        Employee emp = new Employee("John", 10001);

        System.out.println("Hashnode Code before setting emp null: " + System.identityHashCode(emp));

        emp = null; // Removing reference 

        System.out.println("Hashnode Code after setting emp null: " + System.identityHashCode(emp));

    }
}

The result once Run this program:

HashCode before setting emp null: 1304836502
HashCode after setting emp null: 0

Explanation:

  • We've constructed an Employee class as an example.
  • The new keyword was used to create an object. emp is a reference to an employee object.
  • System.identityHashCode(emp) is a method for obtaining non-negative integer values, also known as hashcode.
  • We received Hashcode as 1304836502 before assigning object reference null value.
  • We got Hashcode as 0 after assigning object reference null

Therefore we set null, which indicates the emp object produced above doesn't have any references and will be trash collected to free heap memory.

How do you delete an object from an array in Java?

We can use the same strategy as in the previous example to destroy the selected object by setting null to the object reference.

Consider the following code as an example:

public class Professor {

    private String name;

    private int id;

    public Professor(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {

        return this.name;
    }

    public Integer getId() {

        return this.id;
    }

    public static void main(String[] args) {

        Professor[] arr = new Professor[3];

        arr[0] = new Professor("John", 10001);
        arr[1] = new Professor("Peter", 10002);
        arr[2] = new Professor("Alex", 10003);

        //Let suppose we need to delete Professor with id 10002
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].getId().equals(10002)) {
                arr[i] = null;

            }
        }

        for (int i = 0; i < arr.length; i++) {

            System.out.println(System.identityHashCode(arr[i]));

        }

    }
}

Result:

1304836502
0
225534817

Explanation of the code:

  • Professor constructor was created to set values when building objects.
  • Developed a method To get the id and name of respected objects, use getId and getName.
  • As illustrated above, a formed array of Professor objects has three items.
  • Let's say we need to delete an object with the ID 10002.
  • Loop through the Professor array and check each traversing object element id.
  • Once the condition for id matched with 10002, assigned null to the relevant Professor object reference to destroying the object with id 10002
  • After the previous loop's deletion, print the hashcode for each object reference.
  • The hashcode for an object with id 10002 returns 0 and will be garbage collected

We can use another Professor object to replace a null reference object if necessary.

Please note that the preceding program is only intended to be used as an example. To align with your program's needs, you can apply the appropriate criteria and validation.

How to remove Java objects from a list?

The remove method in Java is used to delete the first occurrence of an object from a given list. It is part of the List interface family.

For a better understanding, below is the demonstration code.

package demo;
import java.util.List;
import java.util.ArrayList;

public class Professor {

    private String name;

    public Professor(String name) {
        this.name = name;
    }

    public String getName() {

        return this.name;
    }

    public static void main(String[] args) {

        List<Professor> listProfessor = new ArrayList<Professor>();

        Professor p1 = new Professor("John");
        Professor p2 = new Professor("Peter");

        listProfessor.add(p1);
        listProfessor.add(p2);

        System.out.println("Before removing an object, print a list of Professor Object names");

        for (Professor p : listProfessor) {
            System.out.println(p.getName());
        }

        listProfessor.remove(p2);

        System.out.println("After removing the object, print a list of Professor Object names");

        for (Professor p : listProfessor) {
            System.out.println(p.getName());
        }

    }
}

Result:

Before removing an object, print a list of Professor Object names
John
Peter

After removing the object, print a list of Professor Object names
John

Explanation of Code:

  • For demonstration reasons, we've constructed a Professor Class with a name attribute.
  • Defined List of Professor objects as List listProfessor = new ArrayList();
  • Created two professor objects and added references in the list of Professor using the list add method
  • Used List remove method to delete the object which contains name peter using listProfessor.remove(p2);
  • The result can be seen both before and after the given object is removed from the list.

Was this post helpful?

Send Feedback

Practice Multiple-Choice Questions

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up