[英]java Generic wildcard “?”
I referred to documentation on Java Generics, and trying to use the wildcard "?" 我提到了关于Java Generics的文档,并试图使用通配符“?” 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;
指的是Unknown类型,因此在类Unknown中,我使用了type-parameter通配符本身; 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.
您必须为通用参数提供有效的Java名称,以便在实现中引用它。
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.
您只能使用Alphabets作为类型参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.