如何使用在方法中的构造函数中初始化的数组?

Mat*_*att -2 java arrays methods constructor

我正在尝试定义一个用户定义的元素数量(度)的数组,然后是一个允许用户一次设置一个元素(系数)的方法.

class Polynomial 
{

    public Polynomial(int degree)
    {
        double[] coef = new double[degree];
    }

    public double[] setCoefficient(int index, double value) 
    {
        coef[index] = value; //coef was set in the constructor
        return coef;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到了编译错误coef[index] = value;.

Era*_*ran 8

您将coef数组定义为构造函数的局部变量,这意味着它不能在其他任何地方使用.

您必须将其定义为实例成员才能从其他方法访问它:

class Polynomial {

    private double[] coef; // declare the array as an instance member

    public Polynomial(int degree) 
    {
        coef = new double[degree]; // initialize the array in the constructor
    }

    public double[] setCoefficient(int index, double value) 
    {
        coef[index] = value; // access the array from any instance method of the class 
        return coef;
    }

}
Run Code Online (Sandbox Code Playgroud)

注意,返回成员变量coefsetCoefficient将允许这个类的用户到阵列直接突变(而不必调用setCoefficient再次方法),这是不是一个好主意.成员变量应该是私有的,并且只能通过包含它们的类的方法进行变更.

因此,我将方法更改为:

public void setCoefficient(int index, double value) 
{
    // you should consider adding a range check here if you want to throw
    // your own custom exception when the provided index is out of bounds
    coef[index] = value;    
}
Run Code Online (Sandbox Code Playgroud)

如果需要从类外部访问数组元素,请添加一个double getCoefficient(int index)返回数组单个值的double[] getCoefficients()方法,或者添加一个返回数组副本的方法.

  • 我不确定为什么`setCoefficient`应该返回该字段.可能值得一提. (3认同)