Reputation: 33389
I've seen an example of it before, but I've never really found any good reference material dealing with it. I know it's possible to pass in several parameters, ints for example, by defining the method as
public void aMethod(int...a)
But I don't know any more about it than that. I've seen an example, and it returned the average of the ints passed.
Is this an out-dated way of passing parameters? Is it even acceptable to use this? What exactly is the syntax like when doing this?
(Some reference material would be great)
Upvotes: 2
Views: 1317
Reputation: 351466
You are going to have to pass a list of ints
to the method to do this, something like this:
public void aMethod(int[] list)
or this:
public void aMethod(ArrayList<int> list)
It would be nice if Java had something like C#'s params
keyword but it doesn't.
Upvotes: -1
Reputation: 5420
It's called varargs (from the C syntax). See Sun's varargs guide for an overview and this JDC Tech Tip for usage. It is not out-dated; it was put in as a feature request since previously you were forced to create an array or list, which was really ugly for supporting something like C's printf.
public void myMethod(String... args) {
for (String aString:args) {
System.out.println(aString);
}
}
Upvotes: 12