clear method in an array

java arrays

6085 просмотра

6 ответа

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?


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 Источник Размещён: 12.11.2019 09:54

Ответы (6)

6 плюса


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

5 плюса

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

1 плюс

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

0 плюса

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

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

0 плюса

list = null


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

-1 плюса

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