java - 如何使用硬编码值声明自定义数据类型的静态数组?

标签 java static-array

目标:

我想为不经常更改的数据实现一个硬编码的查找表,但当它确实发生更改时,我希望能够快速更新程序并重建。

计划:

我的计划是像这样定义一个自定义数据类型...

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;
    }
}

然后,在主类中,像这样对数组进行硬编码......

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

但是,这不会构建。我一直看到消息“Type mismatch: cannot convert from float[] to ScalingData”。

我怎样才能实现我的目标?

更新

到目前为止,我已经尝试实现这些建议,但仍然遇到错误...

代码如下:

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;
        }
    }
}

硬编码数组的错误是

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).

编辑...根据以下答案完成解决方案

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;
        }
    }
}

最佳答案

你不能在 Java 中这样做。您需要像这样使用构造函数:

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

关于java - 如何使用硬编码值声明自定义数据类型的静态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10489038/

相关文章:

java - 有没有办法在java中查询argv的运行时?

java - URL编码的设计方案

c++ - 方法指针的静态数组

php - 将值分配给变量私有(private)静态类属性,该属性是类定义内部的数组

带有静态数组的java空指针异常

java - EXCEPTION_ACCESS_VIOLATION 崩溃的可能原因是什么?

java - 无法在 Java 中的 API 基本身份验证中授权

java - Flex 中没有上传文件

c++ - 创建一个 char 数组,其大小由参数给出 - C++