Java 在变量定义之外声明数组
我正在寻找一种在声明之外直接给java数组一个值的方法,例如
/*this works*/
int a[] = {1,2,3};
/*this doesn't*/
a = {1,2,3};
动机是这样可以像这样使用以数组作为参数的方法
public void f(int a[]) {
/*do stuff*/
}
f({1,2,3});
而不是
int a[] = {1,2,3};
f(a);
I'm looking for a way to give a java array a value directly, outside of its declaration, for example
/*this works*/
int a[] = {1,2,3};
/*this doesn't*/
a = {1,2,3};
the motivation is so that a method with an array as an argument can be used like this
public void f(int a[]) {
/*do stuff*/
}
f({1,2,3});
instead of
int a[] = {1,2,3};
f(a);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试:
Try:
尝试 :
try :
一般来说,你可以说
在代码中的任意位置初始化数组。
In general you can say
to initialize arrays at arbitrary places in the code.
作为更干净的替代方案,您可以使用可变参数功能,这仍然适用于传入数组 - 它只是语法糖。
As a cleaner alternate, you could use the variable parameters functionality, this still works with passing in an array too - it's just syntactic sugar.
您可以使用静态块来执行您想要的操作。请记住,这是第一次加载类时执行的。
You can use a static block to do what you are looking for. Keep in mind that this is executing the first time the class is loaded.