问题描述
我不明白为什么这会让编译器感到困惑。我使用通用类型 T
来存放与放置
和获取方法。我一直认为 GenericClass
和 GenericClass< Object>
在功能上是相同的,但我必须弄错。当编译 DoesntWork
类时,我得到不兼容的类型 - required:String - found:Object
。 Works
类完成我所期望的。这里发生了什么?
I don't understand why this confuses the compiler. I'm using the generic type T
to hold an object that's not related to the put
and get
methods. I always thought GenericClass
and GenericClass<Object>
were functionally identical, but I must be mistaken. When compiling the DoesntWork
class I get incompatible types - required: String - found: Object
. The Works
class does what I expect. What's going on here?
public class GenericClass<T> {
public <V> void put(Class<V> key, V value) {
// put into map
}
public <V> V get(Class<V> key) {
// get from map
return null;
}
public static class DoesntWork {
public DoesntWork() {
GenericClass genericClass = new GenericClass();
String s = genericClass.get(String.class);
}
}
public static class Works {
public Works() {
GenericClass<Object> genericClass = new GenericClass<Object>();
String s = genericClass.get(String.class);
}
}
}
推荐答案
关于原始类型是如何工作的 - 你遗漏了参数的泛型类型 - 它们的所有泛型和它们的方法也被删除。因此,对于原始 GenericClass
, get
和放入
方法 也会失去他们的泛型。
The thing about how raw types work -- generic types that you've left out the arguments for -- is that all generics for them and their methods are erased as well. So for a raw GenericClass
, the get
and put
methods also lose their generics.
这篇关于当我不提供泛型类型时,为什么这个类的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!