#Define equivalent in Java for macros

My question is close to this , but not exactly the same.

I have an inherited (like, for example, I can't / won't change it) parameter array in my class:

public double[] params;

The class uses these parameters in complex ways, so I would prefer to have human-readable names for each element of the array. In C, you would do something like this

#define MY_READABLE_PARAMETER params[0]

I also know that in Java I could create a bunch of constants or an enumerator with attributes. Then, in order to access the parameter, I would have to enter something like this:

params[MY_READABLE_PARAMETER]

This is acceptable, but I would really like to omit the name of the array in general. Is it possible?

+3
source share
4 answers

, , .

public class MyParamBlob extends ParentParamBlob
{
    private double myReadableParameter;
    private double anotherParameter;
    private double yetOneMore;

    // getters and setters as appropriate
}

double[] "", / , .

public class MyParamBlob
{
    ...
    public MyParamBlob(double[] values)
    {
        setAll(values);
    }
    // getters and setters as appropriate
    ...
    public void setAll(double[] values)
    {
        myReadableParameter = values[0];
        anotherParameter = values[1];
        // etc.
    }
}

-

, (, double [] ) getter , , - -

public double[] getParams()
{
    double[] params = new double[4];
    params[0] = myReadableParameter;
    params[1] = anotherParameter;
    // etc.
}

, , , myArray = parentInstance.params double d2 = parentInstance.params[2], (1), (2) - parentInstance.params[1] = 0.0;

+1

, , :

double myReadableParameter;
double anotherReadableParameter;

, .

+3

Is there a reason you could not do this?

...
public double getMyReadableParam() {
    return params[0];
}

public void setMyReadableParam(double value) {
    params[0] = value;
}
...
+3
source

C Enum:

enum Param {
    AGE(0);
    WEIGHT(1);
    ...

    private int arrayIndex;
    // Constructor
    Param(int index) {
        arrayIndex = index;
    }

    public double getValue(double[] params) {
        return params[arrayIndex];
    }
}

and you use it as such

double age = Param.AGE.getValue(params);

I do not think this is better than the other proposals, but I wanted to show how to do it with the help Enum.

+3
source

All Articles