Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Generic wildcard "?"

Tags:

java

generics

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?

like image 980
CuriousMind Avatar asked Feb 12 '23 12:02

CuriousMind


2 Answers

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.
like image 180
Elliott Frisch Avatar answered Feb 15 '23 09:02

Elliott Frisch


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
like image 21
Bohemian Avatar answered Feb 15 '23 09:02

Bohemian