Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method with unlimited arguments

The Spring framework uses methods where you can pass as many arguments as you like.

I would like to write a function that can also take an unlimited amount of data. How is this feature called so that I can read about it? Or how can I define it?

like image 884
Franz Kafka Avatar asked Aug 30 '11 12:08

Franz Kafka


People also ask

How do you pass an infinite argument in Java?

It's called varargs. It allows a method to take any number of arguments. They are accessible as an array in the method: public void foo(String...

How many arguments can a method have Java?

There is a technical maximum of 255 parameters that a method can have.

Can a method have multiple arguments?

Multiple ArgumentsYou can actually have your variable arguments along with other arguments. That is, you can pass your method a double, an int, and then a String using varargs.


1 Answers

It's called varargs.

It allows a method to take any number of arguments. They are accessible as an array in the method:

public void foo(String... args) {     for (String arg : args) {       // do smth with arg.      } } 

This is syntactic sugar. The compiler hides the array creation, so instead of

 bar.foo(new String[] {"1", "2", "3"}); 

you write

 bar.foo("1", "2", "3"); 
like image 171
Bozho Avatar answered Oct 08 '22 06:10

Bozho