views:

298

answers:

5

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);
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[]) {
 ///
}
Chris Dail
Based on the responses, it looks like you are asking for declaring an array not a 'static' array.
Chris Dail
yes. i misused the word static, sorry
Mike
"yes. i misused the word static" -- can you tell us the difference between static and reference? public void f(int a[]) gives you the actual array at the point of the method call, which you can then just use as the actual array.
Nicholas Jordan
+5  A: 

try :

a = new int[]{1,2,3};
akf
woah, creepy. =-o
craig
i declare my individuality via my lowercase t
akf
and the lack of a space between ']' and '{'. i will allow our differences.
craig
+3  A: 

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.

mobrule
+7  A: 

Try:

a = new int[] {1,2,3};
craig
+3  A: 

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});
}
Tom