[JAVA] Variadic argument

I summarized it for personal study

Variadic argument

-Arguments that can freely change the number of arguments -Declare ** immediately after the argument type ** with three ** periods ** "** ... " ・ Theoretically, it can be called by passing any number of arguments. -Multiple values passed are replaced by an array by the JVM. Therefore, when using a value, use " [] **" like an array.

Two points to note

(1) Only arguments with a variable number of the same type can be combined, ** different types cannot be combined ** (2) If it is necessary to receive an argument other than the variable length argument, the variable length argument should be the ** last ** argument.

① is natural considering that variadic arguments are replaced with arrays In (2), for example, in the following method declaration, it is not possible to know where the first argument is and where the second argument is, resulting in a compile error.

Example) Method in which variable length argument is described first (compile error)

sample.java


void sample(int... num,int value) {
	//do something
}

If you change the order as follows, no compile error will occur.

Example) Method in which variable length argument is described last

sample.java


void sample(int value,int... num) {
	//do something
}

Recommended Posts

Variadic argument
[Swift] Variadic arguments