1

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);
2
  • 2
    Do you mean a literal array? This seems to not have anything to do with statics Commented Sep 30, 2009 at 18:09
  • yes "literal array" is the term i was going for. i didn't know the proper name Commented Sep 30, 2009 at 18:14

5 Answers 5

7

Try:

a = new int[] {1,2,3};
Sign up to request clarification or add additional context in comments.

Comments

5

try :

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

2 Comments

i declare my individuality via my lowercase t
and the lack of a space between ']' and '{'. i will allow our differences.
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.

Comments

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

Comments

0

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[]) {
 ///
}

2 Comments

Based on the responses, it looks like you are asking for declaring an array not a 'static' array.
"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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.