Banned
Banned

Reputation: 201

clear method in an array

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..

Upvotes: 2

Views: 8988

Answers (6)

Boris_Ndong
Boris_Ndong

Reputation: 247

public void clearArray(Object[] Array){
    if (Array==null){
        return;
    }
    for (Object ob: Array){
         ob=null;
    }
}

Upvotes: -1

wattostudios
wattostudios

Reputation: 8764

It depends on whether you want to make it a null reference, have size 0, or make all the values = null.

For an array, such as Doctor[], here are some alternatives - not sure which one is applicable for your circumstance...

// setting the array to null
doctors = null;

// removing all array entries, making an array of size 0
doctors = new Doctor[0];

// keeping the array the same size, but making all values = null
doctors = new Doctor[doctors.length];

Upvotes: 2

IT ppl
IT ppl

Reputation: 2647

list = null

or

list = new int[list.length];

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122346

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.

Upvotes: 5

adarshr
adarshr

Reputation: 62583

If it's an array, you need to reinitialize it.

publiv void clear() {
    this.doctors = null;
}

Upvotes: 0

hvgotcodes
hvgotcodes

Reputation: 120188

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];

Upvotes: 6

Related Questions