2013-06-29 9 views
8

Ho trovato questo codice online e c'è una parte che non capisco. Per il metodo doInBackground, il parametro passato è String... params. Qualcuno potrebbe spiegarmi cosa significa? Cos'è quello ...?Cosa significa "String ... params" se passato come parametro?

public class AsyncHttpPost extends AsyncTask<String, String, String> { 
    private HashMap<String, String> mData = null;// post data 

    /** 
    * constructor 
    */ 
    public AsyncHttpPost(HashMap<String, String> data) { 
     mData = data; 
    } 

    /** 
    * background 
    */ 
    @Override 
    protected String doInBackground(String... params) { 
     byte[] result = null; 
     String str = ""; 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL 
     try { 
      // set up post data 
      ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
      Iterator<String> it = mData.keySet().iterator(); 
      while (it.hasNext()) { 
       String key = it.next(); 
       nameValuePair.add(new BasicNameValuePair(key, mData.get(key))); 
      } 

      post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8")); 
      HttpResponse response = client.execute(post); 
      StatusLine statusLine = response.getStatusLine(); 
      if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){ 
       result = EntityUtils.toByteArray(response.getEntity()); 
       str = new String(result, "UTF-8"); 
      } 
     } 
     catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
     catch (Exception e) { 
     } 
     return str; 
    } 

    /** 
    * on getting result 
    */ 
    @Override 
    protected void onPostExecute(String result) { 
     // something... 
    } 
} 
+0

Non si vede dove viene utilizzato? È usato prima sulla quarta riga di themethod. –

+0

params è un nome variabile – barlop

risposta

13

il tre punti rimane per vargars. puoi accedervi come un String[].

Se un metodo prende come paramter un varargs, si può chiamare con più valori per il tipo vargars:

public void myMethod(String... values) {} 

si può chiamare come myMethod("a", "b");

in myMethod values[0] è uguale a "a" e values[1] è uguale a "b". Se si dispone di un metodo con molteplici argomenti, l'argomento vargars deve essere l'ultimo: per esempio: sono passati

public void myMethod(int first, double second, String... values) {} 
+0

Grazie davvero molto aiutato! –

5

Da javadocs:

public static String format(String pattern, 
           Object... arguments); 

I tre periodi successivi al tipo del parametro finale indicano che l'argomento finale può essere passato come una matrice o come una sequenza di argomenti . Varargs può essere utilizzato solo nella posizione dell'argomento finale.

Problemi correlati