在 Java 中创建一个数组并将其作为参数传递
有没有办法创建对象数组作为构造函数或方法的一部分?我真的不知道如何表达,所以我举了一个例子。我有一个枚举,其中一个字段是一组数字。这是我尝试过的:
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
}
}
编译器说括号 { } 无效,应该删除。有没有一种方法可以将数组作为参数传递而无需事先创建对象数组?
Is there a way to create an array of objects as part of a constructor or method? I'm really not sure how to word this, so I've included an example. I have an enum, and one of the fields is an array of numbers. Here is what I tried:
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
}
}
The compiler says that the brackets { } are invalid and should be removed. Is there a way I can pass an array as an argument without creating an array of objects beforehand?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试使用
new float[] { ... }
。You can try with
new float[] { ... }
.按照 @Dave 的建议,我将使用 vararg
使用
float
比使用double
更好的情况很少见。 double 的舍入误差较小,仅多使用 4 个字节。Following @Dave's suggest I would use a vararg
It is pretty rare that using a
float
is better than using adouble
. double has less rounding error and only uses 4 more bytes.有没有一种方法可以在不创建数组的情况下传递数组?
不,但是您可以使用 varargs 来制作它大部分是不可见的,尽管最后的 int 可能需要移动。
Is there a way you can pass an array without creating an array?
No, but you could use varargs to make it mostly-invisible, although that
int
at the end might need to move.如果可以选择使用列表而不是数组,则 Java 的未来版本可能会开始支持“集合文字” ' 语法不幸的是似乎没有进入 Java 8:
If using Lists's instead of arrays is an option, future versions of Java might start supporting a 'collection literals' syntax which unfortunately doesn't seem to have made it into Java 8: