Alex A
Alex A

Reputation: 11

java method to change the value of an array to null

public void setData(double[] d) {
    if (d == null) {
        data = new double[0];
    } else {
        data = new double[d.length];
        for (int i = 0; i < d.length; i++)
            data[i] = d[i];
    }
}

this method in my code is used to set the data of an array. I am also required to write a method called reset() that changes a given array to have a null value. Also, we are practicing overloading in this lab. There are four versions of setData() (double, int, float, long). Since a double array is used internally by the Stat class to store the values, do I only have to make one reset() method of type double?(I think I only need one...) Finally, please give me some hints as to going about this reset business because everything I have tried has failed miserably and usually consists of statements such as "setData(double[] null)" which return errors.

Upvotes: 0

Views: 2621

Answers (3)

isnot2bad
isnot2bad

Reputation: 24444

I'm not sure if I understood your question, but is it that what you want?

public class Stat {
    private double[] data;

    public void reset() {
        data = null;
    }

    public void setData(double[] d) {
        data = (d == null) ? new double[0] : Arrays.copyOf(d, d.length);
    }
}

Upvotes: 0

sandymatt
sandymatt

Reputation: 5612

Because java is pass by value, you can't reassign a variable passed as a parameter to a method, and expect to see that change reflected outside.

What you can do, is put the array in some sort of wrapper class like this:

class ArrayReference<T> {
  T[] array; // T would be either Double, or Long, or Integer, or whatever
}

and then:

void setData(ArrayReference<Double> myReference) {
  myReference.array = null;
}

Upvotes: 0

Steve P.
Steve P.

Reputation: 14699

Everything in java is pass by value; even references are passed by value. So by passing an array through a method, you can change the contents of the array, but you cannot change what the array points to. Now, if you are inside a class and happen to pass an instance member that you already have access to by virtue of being in the class, you will be able to set the array to null.

If you always want to be able to change what an array points to, then simply have a function which returns an array (instead of being void), and assign that returned value to the array of interest.

Upvotes: 1

Related Questions