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?
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With