27

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

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
ufk
  • 30,912
  • 70
  • 235
  • 386

3 Answers3

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) {

}
wkl
  • 77,184
  • 16
  • 165
  • 176
  • if i don't know the type of the argument? can i use just Object ? – ufk Nov 18 '10 at 14:26
  • @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. :) – wkl Nov 18 '10 at 15:24
  • 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 Oct 04 '13 at 01:53
  • 2
    @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`. – wkl Oct 04 '13 at 13:03
  • Is it possible to inherit the class that has the `func(Obj... args)`, but in the child class be more specific in the overriden function? for example: `@Override func(String... args)` or `@Override func(Obj obj1, Obj obj2)` – Makan Jul 17 '19 at 08:55
  • 1
    @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. – wkl Jul 17 '19 at 13:52
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.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
5

Yes, using varargs.

Skilldrick
  • 69,215
  • 34
  • 177
  • 229