Bill Mack Bill Mack - 18 days ago 6
Java Question

Send vector as parameter in Java

This may be a silly problem. I believe it's preety clear what I want to achieve, but I can't think of the syntax for it. Suppose I have:

public void foo(int[] v){

}
public static void main(String args[]){
foo({1, 2, 3});
}


Can I call foo without declaring a new array? If yes, how ?

Answer

Your code doesn't compile the way you wrote it. But this will, and maybe it's what you want:

public void foo(int... v) {
    // ...
}

public static void main(String args[]) {
     foo(1, 2, 3);
}

Here, the values passed to foo will be automatically converted to an array. The value of v will be in fact an int[].

Alternatively, preserving the original signature of foo, you could have written this way:

public void foo(int[] v) {
    // ...
}

public static void main(String args[]) {
     int[] params = {1, 2, 3};
     foo(params);
}

It is not possible to combine those two lines otherwise into foo({1, 2, 3}) as you wrote.

Or you could write this way:

public static void main(String args[]) {
     foo(new int[]{1, 2, 3});
}

The int... syntax I wrote in the first version is called "varargs", if you want to read more about it. As you are a beginner, I don't recommend to use it, as you may experience some pitfalls, and it may be more confusing than useful. Stick to the second or third versions for now.

Comments