6

for example I have a code like this: (from here)

private class LongOperation extends AsyncTask<String, Void, String> {

      @Override
      protected String doInBackground(String... params) {}      

      @Override
      protected void onPostExecute(String result) {}

      @Override
      protected void onPreExecute() {}

      @Override
      protected void onProgressUpdate(Void... values) {
      }
}

and what do the 3 dots in the parameter of the method do?

Community
  • 1
  • 1
maysi
  • 5,457
  • 12
  • 34
  • 62

3 Answers3

9

The three dots are referred to as varargs and here, allow you to pass more than one string to the method like so:

doInBackground("hello","world");
//you can also do this:
doInBackground(new String[]{"hello","world"});

Documentation on that here.

Within the method doInBackground you can enumerate over the varargs variable, params like so:

for(int i=0;i<params.length;i++){
    System.out.println(params[i]);
}

So its basically an array of strings within the scope of doInBackground

William Morrison
  • 10,953
  • 2
  • 31
  • 48
  • ok. and how do I access to this strings? just like an array? – maysi Jul 12 '13 at 20:13
  • 2
    @Simon Yup. In fact, at runtime it _is_ just an array, and not even a special one. The `...` stuff is purely compile-time syntactic sugar. You can even invoke the method by passing it a `String[]` (or whatever) instead of a bunch of `String`s, as this answer shows. – yshavit Jul 12 '13 at 20:16
4

The compiler treats the three dots ... as taking in an array of that object. In this case String and Void. The amount of objects you pass in is the size of the array.

Thus:

doInBackground("Hi", "Hello", "Bye") will create an array of String of length 3.

chancea
  • 5,858
  • 3
  • 29
  • 39
  • so void will generate an array of the type Object? – maysi Jul 12 '13 at 20:16
  • 1
    @Simon not `void` this is `Void` it is an object itself different that the `void` your thinking of – chancea Jul 12 '13 at 20:17
  • Okay and parameters like `Void... objects` would be the same as `Object[] objects` ? – maysi Jul 12 '13 at 20:20
  • 1
    @Simon no the `Void` class is different than the `Object` class. Look at http://stackoverflow.com/questions/643906/uses-for-the-java-void-reference-type – chancea Jul 12 '13 at 20:21
2

This concept is called varargs and explained here

Michael Lang
  • 3,902
  • 1
  • 23
  • 37