javastatic-array

How does one declare a static array of custom data type with hard-coded values?


Goal:

I want to implement a hard-coded lookup table for data that doesn't change often, but when it does change I want to be able to quickly update the program and rebuild.

Plan:

My plan was to define a custom data type like so...

private class ScalingData
{
    public float mAmount;
    public String mPurpose;
    public int mPriority;

    ScalingData(float fAmount, String strPurpose, int iPriority)
    {
        mAmount = fAmount;
        mPurpose = strPurpose;
        mPriority = iPriority;
    }
}

and then, in the main class, hard-code the array like so ...

public static ScalingData[] ScalingDataArray =
{
        {1.01f, "Data point 1", 1},
        {1.55f, "Data point 2", 2}
};

However, this doesn't build. I keep seeing the message "Type mismatch: cannot convert from float[] to ScalingData".

How can I achieve my objective ?

UPDATE

I've attempted to implement the suggestions so far, but still running into an error...

The code looks like:

public class CustomConverter
{
    //Lookup Table
    private static ScalingData[] ScalingDataArray =
    {
        new ScalingData(1.01f, "Data point 1", 1),
        new ScalingData(1.55f, "Data point 2", 2)
    };


    //Constructor
    CustomConverter()
    {
        //does stuff
    }


    //Custom Data type
    private class ScalingData
    {
        public float mAmount;
        public String mPurpose;
        public int mPriority;

        ScalingData(float fAmount, String strPurpose, int iPriority)
        {
            mAmount = fAmount;
            mPurpose = strPurpose;
            mPriority = iPriority;
        }
    }
}

and the error with the hard-coded array is

No enclosing instance of type CustomConverter is accessible.
   Must qualify the allocation with an enclosing instance of type CustomConverter
   (e.g. x.new A() where x is an instance of CustomConverter).

EDIT... complete solution as per answers below

public class CustomConverter
{
    //Lookup Table
    private static ScalingData[] ScalingDataArray =
    {
        new ScalingData(1.01f, "Data point 1", 1),
        new ScalingData(1.55f, "Data point 2", 2)
    };


    //Constructor
    CustomConverter()
    {
        //does stuff
    }


    //Custom Data type
    private static class ScalingData
    {
        public float mAmount;
        public String mPurpose;
        public int mPriority;

        ScalingData(float fAmount, String strPurpose, int iPriority)
        {
            mAmount = fAmount;
            mPurpose = strPurpose;
            mPriority = iPriority;
        }
    }
}

Solution

  • You can't do that in Java. You need to use the constructor like so:

    public static ScalingData[] ScalingDataArray =
    {
            new ScalingData(1.01f, "Data point 1", 1),
            new ScalingData(1.55f, "Data point 2", 2)
    };