- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个关于 Java 泛型的问题,即使用通配符。我有一个像这样的示例类 GenClass:
public class GenClass<E> {
private E var;
public void setVar(E x) {
var = x;
}
public E getVar() {
return var;
}
}
我还有一个简单的类:
public class ExampleClass {
}
我写了下面的测试类:
public class TestGenClass {
public static void main(String[] str) {
ExampleClass ec = new ExampleClass();
GenClass<ExampleClass> c = new GenClass<ExampleClass>();
c.setVar(ec);
System.out.println(c.getVar()); // OUTPUT: ExampleClass@addbf1
}
}
现在,如果我使用通配符并在测试类中这样写:
GenClass<?> c = new GenClass<ExampleClass>();
在:
GenClass<ExampleClass> c = new GenClass<ExampleClass>();
编译器对这个新语句没有问题,但是,它会提示
c.setVar(ec);
它表示“方法 (setVar()) 不适用于参数 (ExampleClass)”。为什么我会收到这条消息?
我认为我使用通配符的方式使引用变量 c 成为 GenClass 类型,它可以接受任何类作为参数 - 在 E 的位置我可以有任何类。这只是变量的声明。然后我用
初始化它new GenClass<ExampleClass>()
这意味着我创建了一个 GenClass 类型的对象,它的参数是一个 ExampleClass 类型的类。所以,我认为现在 GenClass 中的 E 将是 ExampleClass,并且我将能够使用方法 setVar(),将其作为 ExampleClass 类型的参数。这是我的假设和理解,但似乎Java不喜欢它,我也不对。感谢任何评论,谢谢。
最佳答案
Java Generics Tutorial 中涵盖了这种确切情况。 .
Notice that [with the wildcard], we can still read elements from [the generic
Collection
] and give them typeObject
. This is always safe, since whatever the actual type of the collection, it does contain objects. It isn't safe to add arbitrary objects to it however:
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error
Since we don't know what the element type of
c
stands for, we cannot add objects to it. Theadd()
method takes arguments of typeE
, the element type of the collection. When the actual type parameter is?
, it stands for some unknown type. Any parameter we pass toadd
would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception isnull
, which is a member of every type.
(强调我的)
关于java - Java 中的泛型,使用通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/503721/
我是一名优秀的程序员,十分优秀!