How to define a method that can take arbitrary arguments in java? Is there a demo?
varargs were introduced in Java 5.
For instance:
public String join(String... parts);
This is actually a shortcut for:
public String join(String[] parts);
the parts
parameter is used as an array in the method, but the method can be called without constructing an array (like obj.join(new String[] {part1, part2, part3})
)
However be very careful with this, because ambiguities can arise. For example:
public void write(String author, String... words);
public void write(String... words);
Which method will be called if obj.write("Mike", "jumps")
? The compiler is clever enough to detect the ambiguity, but I've had cases when some compilers did not spot such problems (can't recall exactly)
Using varargs is practical when the objects are of the same type, or at least with the same functional aim. If you want different arguments. For example:
public String publishBook(String title, [String author],
[String isbn], [boolean hardcover]); // [..] would mean optional
then you need to overload your method
Variable-Length Argument Lists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With