Biggy_java
Biggy_java

Reputation: 465

Generic variable number of parameter passing in java

I have a method findByProperties(Parameter... p); so it can take any number of parameters. But what I am confused is if I had to call this method and I do not know the number of parameters how do I do that

suppose I have a list with parameters, and the size of the list changes each time you call the method, the how would I add the parameters from the list to the method call?

for(ArrayList<Parameter> p : list){
   findByProperties(p);  //not sure what to do here
 }

EDIT:

this was the solution:

Parameter[] paramArray = new ArrayList<Parameter>().toArray(new Parameter[]{});
findByProperties(paramArray);

Upvotes: 2

Views: 2197

Answers (5)

matts
matts

Reputation: 6887

In Java, you can also pass in an array for a method with a variable argument. So you can use the toArray method of the parameter list to convert the List<Parameter> to a Parameter[], which can be passed directly to findByProperties:

for (ArrayList<Parameter> p : list){
    Parameter[] param = p.toArray(new Parameter[p.size()])
    findByProperties(param);
}

If you need to do this other places too, you could also make a convenience method:

public ... findByProperties(List<Parameter> p) {
    return findByProperties(p.toArray(new Parameter[p.size()]));
}

Upvotes: 1

RAj
RAj

Reputation: 38

findByProperties(Parameter... p);

u can invoke the method findByProperties(); (or) findByProperties(p);

but not findByProperties(p,p,p);

Upvotes: 1

Andy
Andy

Reputation: 1994

You can do something like this:

Parameter[] paramArray = new ArrayList<Parameter>().toArray(new Parameter[]{});
findByProperties(paramArray);

It's the same as something like:

findProperties(param1, param2);

Because Java internally transforms a varargs-list into an array, so you can pass an array, too.

Upvotes: 4

Ted Hopp
Ted Hopp

Reputation: 234795

You can override findByProperties to take either varargs or a List<Parameter>. One can then relay to the other:

void findByProperties(Parameter... p) {
    findByProperties(Arrays.asList(p));
}

void findByProperties(List<Parameter> p) {
    . . .
}

Then you can call findByProperties with either a variable argument list of Parameter objects, or with a List<Parameter> argument. Using Arrays.asList does not create a new array; it just wraps the existing array in a List implementation; thus, this is less work than creating a new Parameter[] array from the list.

Upvotes: 3

Cisco
Cisco

Reputation: 532

Methods can declare a parameter that accepts from zero to many arguments, a so-called var-arg method.

A var-arg parameter is decalared with the sintax type... name; for instance:

doSomething(int... x){}

Upvotes: 1

Related Questions