java – 如何使用硬编码值声明自定义数据类型的静态数组?
作者:互联网
目标:
我想为不经常更改的数据实现硬编码查找表,但是当它确实发生更改时,我希望能够快速更新程序并重建.
计划:
我的计划是定义一个自定义数据类型…
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}
};
但是,这不构建.我一直看到消息“类型不匹配:无法从float []转换为ScalingData”.
我怎样才能实现目标?
UPDATE
到目前为止,我已尝试实施这些建议,但仍然遇到错误……
代码如下:
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,static-array 来源: https://codeday.me/bug/20190726/1538969.html