clear method in an array

java arrays

6085 просмотра

6 ответа

121 Репутация автора

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

Автор: Banned Источник Размещён: 22.03.2012 12:19

Ответы (6)


6 плюса

97851 Репутация автора

Решение

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

Автор: hvgotcodes Размещён: 22.03.2012 12:22

0 плюса

51432 Репутация автора

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

publiv void clear() {
    this.doctors = null;
}
Автор: adarshr Размещён: 22.03.2012 12:22

5 плюса

90295 Репутация автора

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.

Автор: Simeon Visser Размещён: 22.03.2012 12:23

0 плюса

2283 Репутация автора

list = null

or

list = new int[list.length];
Автор: IT ppl Размещён: 22.03.2012 12:26

1 плюс

8027 Репутация автора

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];
Автор: wattostudios Размещён: 22.03.2012 12:28

-1 плюса

121 Репутация автора

public void clearArray(Object[] Array){
    if (Array==null){
        return;
    }
    for (Object ob: Array){
         ob=null;
    }
}
Автор: Boris_Ndong Размещён: 21.09.2017 03:53
Вопросы из категории :
32x32