Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear method in an array

Tags:

java

arrays

I am trying to create a clear method that would clear the array I have, I've seen that using a clear method is what I need but I cannot seem to use it?

 list.clear();

What I think I have to do:

public void clear() {
        return doctors.clear();
    }

doctors are an array by the way.

However I think I am thinking about this incorrectly..

like image 316
Banned Avatar asked May 08 '26 17:05

Banned


2 Answers

An array is not a List. There is no clear method. You can clear one by assigning a null reference, and let the garbage collector take care of it...

yourArray = null;

or create a new array, and replace the old with the new. The old one will be garbage collected.

yourArray = new YourObject[n];

like image 181
hvgotcodes Avatar answered May 10 '26 11:05

hvgotcodes


You can simply create a new empty array and assign that:

doctors = new Doctor[size];

The array will be defined but the objects will not be created yet.

like image 21
Simeon Visser Avatar answered May 10 '26 12:05

Simeon Visser