When programming for android, whenever I use an AsyncTask the doInBackground method looks like this.
protected String doInBackground(String... args)
But when using the arguments anywhere in that block I can access them like a normal String array for example in my program
@Override
protected String doInBackground(String... args)
{
String details = "";
try
{
details = facade.getRecipeDetails(args[0]);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return details;
}
Which works fine and I have no problem dealing with it. But I'm wondering why they use (String . . . args) instead of a normal array of Strings. Is it just because in the calling method you can just write something like:
new AsyncHandler.execute("argument1","argument2","argument3",...)
instead of creating a new array to pass the arguments? Though we could write
new AsyncHandler().execute(new String[]{"Argument1","Argument2"});
which is a bit more verbose.
Are (String …) and String[] synonymous in how they work, but the argument passing is just easier using the former because there is no need to create an array? As far as I can tell, the former also gets translated to a string array in the background so would they both compile to the same code and it's just 'syntactic sugar'?
Best Answer
(String ...)
is an array of parameters of typeString
, where asString[]
is a single parameter.Now here
String[]
can full fill the same purpose here but(String ...)
provides more readability and easiness to use.It also provides an option that we can pass multiple array of
String
rather than a single one usingString[]
.