Java 函数参数中3个点的含义是什么?

Java 函数参数中3个点的含义是什么?,java,android,android-asynctask,Java,Android,Android Asynctask,我在读android文档中关于AsyncTask的内容 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i <

我在读android文档中关于AsyncTask的内容

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
私有类下载文件任务扩展异步任务{
受保护的长doInBackground(URL…URL){
int count=url.length;
长totalSize=0;
for(int i=0;i

问题是
doInBackground(URL…URL)
这三个点是什么

这意味着该函数接受可变数量的参数-它是可变的。例如,所有这些都是有效的调用(假设它绑定到
AsyncTask
的实例):

在方法体中,
url
基本上是一个数组。关于varargs的一个有趣的事情是,您可以通过两种方式调用这种方法——要么传递一个参数数组,要么将每个url指定为一个单独的方法参数。因此,这两者是等价的:

this.doInBackground(url1, url2, url3);
this.doInBackground(new URL[] {url1, url2, url3});
您可以使用for循环遍历所有这些项:

protected Long doInBackground(URL... urls) {
  for (URL url : urls) {
    // Do something with url
  }
}

当然,您可以自己定义类似的方法,例如:

this.doInBackground();                 // Yes, you could pass no argument
                                       // and it'd be still valid.
this.doInBackground(url1);
this.doInBackground(url1, url2);
this.doInBackground(url1, url2, url3);
// ...
public void addPerson (String name, String... friends) {
  // ...
}
在本例中,您的方法将接受一个强制参数(
name
,您不能使用此参数)和可变数量的
friends
参数:

this.addPerson();               // INVALID, name not given
this.addPerson("John");         // Valid, but no friends given.
this.addPerson("John," "Kate"); // Valid, name is John and one friend - Kate


并不是说这个构造在Java5之后就可用了。您可以找到文档。

这三个点表示函数的可变长度参数

这三个点意味着可以使用progress[0]或progress[1]等将不同数量的参数传递给我们访问的函数

由于Stackoverflow上已经存在多个重复项,因此该问题的研究工作很少:


这不是Android的功能。这是一个Java特性(在Java5中添加),它是为了让您可以拥有“自定义”参数而包含的

此方法:

protected Long doInBackground(URL... urls) {
  for (URL url : urls) {
    // Do something with url
  }
}
还有这个:

protected Long doInBackground(URL[] urls) {
  for (URL url : urls) {
    // Do something with url
  }
}
对于内部方法是相同的。 整个区别在于你调用它的方式。 对于第一个(也称为varargs),您可以简单地执行以下操作:

doInBackground(url1,url2,url3,url4);
但在第二行中,您必须创建一个数组,因此,如果您尝试在一行中执行此操作,它将如下所示:

doInBackground(new URL[] { url1, url2, url3 });

好的方面是,如果您尝试以这种方式调用使用varargs编写的方法,它的工作方式将与不使用varargs的方法相同(向后支持).

你能进一步解释一下吗?它是指只有3个变量还是任意数量的变量?它意味着你可以传递零个或多个参数。它是指只有3个变量还是任意数量的变量?它意味着一个由零个或多个元素组成的数组。这可能是一个注释,而不是答案!