views:

3601

answers:

2

In c# if you want a method to have an indeterminate number of parameters you can make the final parameter in the method signature a "params" which to the method looks like an array but allows anyone using the method to put in as many parameters of that type as the want.

I'm fairly sure java supports similar behaviour, but I cant find out how to do it.

+32  A: 

In Java it's called varargs, and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:

public void foo(Object... bar) {
    for (Object baz : bar) {
        System.out.println(baz.toString());
    }
}

The vararg parameter must always be the last parameter in the method signature, and is accessed as if you received an array of that type (e.g. Object[] in this case).

David Grant
Thanks I bizzarrly found this out myself while I was looking up something else, and was coming here to answer the question myself.
Omar Kooheji
+4  A: 

This will do the trick in Java public void foo(String parameter, Object... arguments);

You have to add three points "..." and the varagr parameter must be the last in the method's signature

Stefano Driussi