如果作为参数传递,“String ... params”是什么意思?

时间:2013-06-29 16:58:32

标签: java android

我在网上发现了这个代码,有一部分我不明白。对于方法doInBackground,传递的参数是String... params。有人可以向我解释一下这意味着什么?什么是...

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...
    }
}

3 个答案:

答案 0 :(得分:18)

vargars的三个点。您可以像String[]一样访问它。

如果某个方法采用varargs作为参数,则可以使用vargars类型的多个值来调用它:

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

你可以像myMethod("a", "b");

一样打电话 myMethod values[0]中的

等于“a”,values[1]等于“b”。如果你有一个带有多个args的方法,那么vargars参数必须是最后一个:例如:

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

答案 1 :(得分:11)

 doInBackground(String... params)
 // params represents a vararg.
 new AsyncHttpPost().execute(s1,s2,s3); // pass strings to doInbackground
 params[0] is the first string
 params[1]  is the second string 
 params[2]  is the third string 

http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground(Params...)

异步任务的参数传递给doInBackground

答案 2 :(得分:6)

来自javadocs

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

最终参数类型后的三个句点表示   final参数可以作为数组或序列传递   参数。 Varargs只能在最终的参数位置使用。