简体   繁体   中英

java Generic wildcard “?”

I referred to documentation on Java Generics, and trying to use the wildcard "?" in a simple program:

class Unknown <?> {

}

public class UnknownTypes {

    public static void main(String s[] ) {

    }
}

Wildcard "?" refers to an Unknown type, so in class Unknown, I used type-parameter wildcard itself; however when I compile I get compilation error. If I had used like this it would have worked.

class Unknown <T> {

}

If wildcard "?" refers to unknown type, why can't we use "?" as type parameter.

The following is the compile error that I get.

UnknownTypes.java:1: error: <identifier> expected
class Unknown <?> {
           ^
UnknownTypes.java:1: error: '{' expected
class Unknown <?> {
            ^
UnknownTypes.java:10: error: reached end of file while parsing
}

Is wildcard "?" used in conjunction with something else?

You can't name a generic parameter as ? , because ? is not a valid identifier - a valid name of a variable. You have to give a generic parameter a valid java name so you can refer to it in the implementation.

You can only specify ? as a generic bound:

List<?> list; // a variable holding a reference to a list of unknown type

You can't use ? when creating an instance:

new ArrayList<?>(); // can't do this

or as a parameter name of a class :

class MyClass<?> { // can't do this

To define a generic class with a type parameter, you cannot use a wildcard (in the generic class it is a type)

class Unknown <TYPE> {
  TYPE foo; // <-- specifies the type of foo.
}

When using it, you can use the wildcard

Unknown<?> some = new Unknown<String>(); // <-- some is any kind of Unknown.

You only use the wildcard when referring to an instance of a class. Not in the class declaration.

class Unknown<T>{}

Unknown<?> instance= new Unknown<Integer>();


public void canHandleAnyUnknown(Unknown<?> wild){
}

Wildcard means 'anything' not unknown. You can use only Alphabets as type parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM