Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a method that can take arbitrary arguments in java?

Tags:

java

How to define a method that can take arbitrary arguments in java? Is there a demo?

like image 863
symfony Avatar asked Dec 06 '22 03:12

symfony


2 Answers

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

like image 76
Bozho Avatar answered Dec 07 '22 16:12

Bozho


Variable-Length Argument Lists

like image 40
aJ. Avatar answered Dec 07 '22 15:12

aJ.