28

is it possible to create a function in java that supports any number of parameters and then to be able to iterate through each of the parameter provided to the function ?

thanks

kfir

3 Answers 3

49

Java has had varargs since Java 1.5 (released September 2004).

A simple example looks like this...

public void func(String ... strings) {
    for (String s : strings)
         System.out.println(s);
}

Note that if you wanted to require that some minimal number of arguments has to be passed to a function, while still allowing for variable arguments, you should do something like this. For example, if you had a function that needed at least one string, and then a variable length argument list:

public void func2(String s1, String ... strings) {

}
Sign up to request clarification or add additional context in comments.

6 Comments

if i don't know the type of the argument? can i use just Object ?
@ufk - as aiiobe says, you can do that. But you will have to handle the work of checking for type and doing whatever casting you need. As Bloch writes in Effective Java, use varargs judiciously. :)
What about any number of any type of parameter? Would it just be (Object... args)? Does that support passing primities? Do they get boxed?
@trusktr Yes, you could declare a func(Object... args) signature to support a variable number of generic Object. If you passed a primitive to the function, it will be autoboxed into its corresponding wrapper class. Calling func(1,2,3.0) will autobox the first two arguments into Integer, and the third into Double.
@MakanTayebi you can overload the method in the subclass and give it the same name but with different parameters, but using @Override would cause a compilation error because overriding would require the method signature in the subclass to be the same as the method in the parent.
|
7

As other have pointed out you can use Varargs:

void myMethod(Object... args) 

This is actually equivalent to:

void myMethod(Object[] args) 

In fact the compiler converts the first form to the second - there is no difference in byte code. All arguments must be of the same type, so if you want to use arguments with different types you need to use an Object type and do the necessary casting.

Comments

5

Yes, using varargs.

Comments

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.