Java syntax <?> explanation

2020-05-07 19:56发布

问题:

Hi I came across a code in documentation of android in Grid view for the following code.

gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });

In this what does the < ?> (space added as stackoverflow didn't allow without space) indicate/do?

回答1:

The < ? > is a wild card for the generic type, meaning the generic type for AdapterView can be anything at all.

More specifically in this case the parameter on the method may receive an AdapterView with absolutely any generic type. As a note if you wanted to limit the generic type you could do:

AdapterView<? extends myClass)

This limits the generic type to myClass or anything that extends myClass.

Just as a note:

 AdapterView <?> and AdapterView<? extends Object> 

Are identical.

You can find additional information here in the wildcards section

Java generics documentation