有没有办法在构造函数或方法中创建对象数组?我真的不确定怎么说这个,所以我举了一个例子。我有一个枚举,其中一个字段是数字数组。这是我试过的:
public enum KeyboardStuff {
QWERTY(1, {0.5f, 1.3f, 23.1f}, 6);
DVORAK(5, {0.1f, 0.2f, 4.3f, 1.1f}, 91);
CHEROKEE(2, {22.0f}, 11);
private int number, thingy;
private float[] theArray;
private KeyboardStuff(int i, float[] anArray, int j) {
// do things
}
}
编译器说括号{}无效,应删除。有没有办法可以在不事先创建对象数组的情况下将数组作为参数传递?
答案 0 :(得分:34)
您可以尝试new float[] { ... }
。
public enum KeyboardStuff {
QWERTY(1, new float[] {0.5f, 1.3f, 23.1f}, 6);
DVORAK(5, new float[] {0.1f, 0.2f, 4.3f, 1.1f}, 91);
CHEROKEE(2, new float[] {22.0f}, 11);
private int number, thingy;
private float[] theArray;
private KeyboardStuff(int i, float[] anArray, int j) {
// do things
}
}
答案 1 :(得分:5)
关注@ Dave的建议我会使用vararg
QWERTY(1, 6, 0.5, 1.3, 23.1);
DVORAK(5, 91, 0.1, 0.2, 4.3, 1.1);
CHEROKEE(2, 11, 22.0);
private final int number, thingy;
private final double[] theArray;
private KeyboardStuff(int number, int thingy, double... theArray) {
// do things
}
使用float
比使用double
要好得多。 double有更少的舍入误差,只使用4个字节。
答案 2 :(得分:2)
有没有办法可以在不创建数组的情况下传递数组?
不,但您可以使用varargs使其大部分不可见,但最后int
可能需要移动。
答案 3 :(得分:1)
如果使用Lists而不是数组是一个选项,Java的未来版本可能会开始支持“collection literals”语法,遗憾的是它似乎没有进入Java 8:
public enum KeyboardStuff {
QWERTY(1, [0.5f, 1.3f, 23.1f], 6);
DVORAK(5, [0.1f, 0.2f, 4.3f, 1.1f], 91);
CHEROKEE(2, [22.0f], 11);
private int number, thingy;
private List<Float> values;
private KeyboardStuff(int i, List<Float> values, int j) {
// do things
}
}