I was seeing some methods of the javax
package classes and some of them have a signature similar to this:
protected void doInBackground(String... params){}
What does this " ...
" mean??
I was seeing some methods of the javax
package classes and some of them have a signature similar to this:
protected void doInBackground(String... params){}
What does this " ...
" mean??
What you have in the example mentioned is the definition that the params
parameter will receive the arguments in an array of Strings from Java 5.0+ (this definition is known as " varargs ").
In other words, you can have a variable number of arguments in the function call from where ...
was specified.
This syntax can be used merged with "normal" parameters:
void teste( String a, Integer... b ) {
//...
}
teste( "a" ); // a recebe "a", b fica vazio
teste( "a", 1, 2 ); // a recebe "a", b recebe { 1, 2 }
And, if you want to use various types in the arguments:
void teste( String a, Object... b ) {
//...
}
teste( "a", 1, "x", 7 ); // a recebe "a", b recebe { 1, "x", 7 }
Note that in this case, you are missing the compile-time check in b
because the object accepts different types in the arguments, and you should usually do this runtime checking to sanitize the values and to be able to use them with tranquility.
Note : This answer I initially gave in a question that was later identified as a copy of this question from here. As the answers given in this question do not exemplify how to use varargs (just like calling), then I think this answer complements those of @Bacco and @Cold.
The ...
is called ellipsis or varargs, within teste
, obj
will have the same behavior as a vector. For example:
public void teste(Object... obj) {
for (int I = 0; I < obj.length; i++) {
Object atual = obj[i];
System.out.println(i + "-esimo elemento: " + atual);
}
}
To call teste
, however, you do not need to instantiate a vector. You could do this:
teste("primeiro parâmetro", Integer.valueOf(1), null, BigDecimal.TEN);
The notation ...
(three points, which in Portuguese is known as "ellipsis") is known in Java as varargs . It allows a method to accept an indefinite number of parameters of a certain type.
In your case:
protected void doInBackground(String... params){}
This method accepts an undefined number of parameters of type String
.
When you receive this params
in your method, you can read its contents by treating params
as any array . So by calling the method as follows:
doInBackground("Joao", "Pedro", "Paulo");
We will have:
protected void doInBackground(String... params){
if (params.length > 0) {
String paramZero = params[0];
System.out.println(paramZero); // imprimirá 'João'
}
}
Despite its flexibility, varargs have some limitations and risks:
Object
to the variables of the log message, but it internally checks if the last parameter inside the varargs is some kind of exception, to log the same;