lemotdit lemotdit - 14 days ago 6
Java Question

public void add(int a, int... b) {

Could someone show me a practical a use of the ... array method delcaration?
Is it just a way to declare an optional parameter instead of passing null value?

public void add(int a, int... b) {
// do something
}

add(1);
add(1,2,3);

Answer

It's a shorthand for you when you're writing code that will use a function that can take an array as a parameter.

It's generally easier to write add(1,2,3,4); than it is to write add(new int[] {1,2,3,4});, right? It's also clearer when it needs to be read and maintained by future programmers later.

Think about it this way: which function would you call, the one where you have to create an array every time, or the one where you can just pass in as many parameters as you want?

Comments