Java 在变量定义之外声明数组

发布于 2024-08-06 10:51:54 字数 302 浏览 6 评论 0原文

我正在寻找一种在声明之外直接给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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

蓝礼 2024-08-13 10:51:54

尝试:

a = new int[] {1,2,3};

Try:

a = new int[] {1,2,3};
阳光下慵懒的猫 2024-08-13 10:51:54

尝试 :

a = new int[]{1,2,3};

try :

a = new int[]{1,2,3};
谷夏 2024-08-13 10:51:54

一般来说,你可以说

int[] a;
a = new int[]{1,2,3};

 

public void f(int a[]) { ... }

f(new int[]{1,2,3})

在代码中的任意位置初始化数组。

In general you can say

int[] a;
a = new int[]{1,2,3};

 

public void f(int a[]) { ... }

f(new int[]{1,2,3})

to initialize arrays at arbitrary places in the code.

梦醒时光 2024-08-13 10:51:54

作为更干净的替代方案,您可以使用可变参数功能,这仍然适用于传入数组 - 它只是语法糖。

public void f(int... a) {
    /*do stuff*/
}

public void test() {
    f(1);
    f(1,2,3);
    f(new int[]{1,2,3});
}

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.

public void f(int... a) {
    /*do stuff*/
}

public void test() {
    f(1);
    f(1,2,3);
    f(new int[]{1,2,3});
}
感受沵的脚步 2024-08-13 10:51:54

您可以使用静态块来执行您想要的操作。请记住,这是第一次加载类时执行的。

private static int a[];

static {
    a = new int[] {1,2,3};
    f(new int[]{1,2,3}); 
}

public static void f(int a[]) {
 ///
}

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.

private static int a[];

static {
    a = new int[] {1,2,3};
    f(new int[]{1,2,3}); 
}

public static void f(int a[]) {
 ///
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文