Tan*_*aki 19 java arrays parameters arguments argument-passing
有没有办法创建一个对象数组作为构造函数或方法的一部分?我真的不确定怎么说这个,所以我举了一个例子.我有一个枚举,其中一个字段是数字数组.这是我尝试过的:
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
}
}
Run Code Online (Sandbox Code Playgroud)
编译器说括号{}无效,应该删除.有没有一种方法可以将数组作为参数传递而不事先创建对象数组?
Viv*_*sse 36
你可以试试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
}
}
Run Code Online (Sandbox Code Playgroud)
关注@ 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
}
Run Code Online (Sandbox Code Playgroud)
使用a float比使用a更好是非常罕见的double.double具有较少的舍入误差,仅使用4个字节.