Java 泛型——这个语法有什么用?

标签 java android generics

下面这部分代码是什么<String, Void, Bitmap>意思是?我什至不知道这种语法叫什么。

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

}



这是原始代码(从此处找到:http://developer.android.com/guide/components/processes-and-threads.html):

public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }

    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}

最佳答案

AsyncTask<String, Void, Bitmap>

当您使用 AsyncTask 时,告诉 AsyncTask 由 3 种不同的类型描述,String 作为第一个参数,Void 作为第二个参数,Bitmap 作为第三个参数。

这叫做 Generics在java中,从Java5开始引入。请阅读此tutorial了解更多关于泛型的信息。这是 javadoc关于 android AsyncTasktask 如何使用泛型。

更新:来自 AsyncTask javadoc

1) Params, the type of the parameters sent to the task upon execution.
2) Progress, the type of the progress units published during the background computation.
3) Result, the type of the result of the background computation.

关于Java 泛型——这个语法有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13238150/

相关文章:

java - 如果 Firebase 数据库 ID 存在,则通知用户

TypeScript 泛型 - 类型推断

java - Eclipse 工作区在每次关闭时都会损坏

java - JTable 列值的总和以及总和显示在最后一行

Java : how can i remove array of words from a LinkedList<ArrayList<String>>

java - 下载大型视频文件被损坏

android - 从Android Studio读取txt、mp3等文件

java - Android 中的平面图实现

ios - 将 ViewController 与 swift 中的类型进行比较

java - 实现其中包含其他通用定义的原始接口(interface)