英文:
Generic method upper bound isn't checked
问题
我创建了一个带有两个类型参数的通用方法,如下所示,位于非通用类内部:
static <T, V extends T> boolean testMethod(T t, V[] v) {
return true;
}
第二个类型参数定义为 V extends T
。
现在考虑使用以下参数调用此方法:
testMethod("text", new Integer[]{1, 2});
当我尝试使用上述参数调用此方法时,我预期会得到类型不匹配的错误,因为类型参数 T
被替代为 String
,而 V
被替代为 Integer
,如您所见,V
受到了 T
的限制,这意味着它必须是 String 类型或其派生类之一,但 Integer 不是它们之一。但是,这段代码编译并成功运行,没有任何问题。
有人能解释一下我对这个概念的印象错在哪里吗?
英文:
I've created a generic method with two type paremeter as follow inside a non-generic class:
static <T, V extends T> boolean testMethod(T t, V[] v) {
return true;
}
The second type parameter defined as V extends T
.
Now consider calling of this method by following arguments:
testMethod("text", new Integer[]{1, 2});
When I try to call this method with the above parameters I expected to got an error of type mismatch, because type parameter T
substituted by String
and V
substituted by Integer
and as you see V
is bounded by T
which means it must be of type String or its derived classes but Integer is non of them. But the code segment compile and run successfully without any problem.
Can somebody explain what is wrong about my impression of this concept?
答案1
得分: 8
在这个方法调用中,T
和 V
类型参数的值没有明确提供,因此编译器会自动推断它们。即使结果有时并不直观,它也会尝试推断出有效的替代项而不返回错误。在这个例子中,值 "text"
是一个 String
,但它也是一个 Object
。由于推断 T = String, V = Integer
是无效的,因为 Integer
不是 String
的子类型,所以编译器使用 T = Object, V = Integer
,这是有效的。
英文:
In this method call, the values of the T
and V
type parameters are not provided explicitly, so the compiler infers them. It will always try to infer valid substitutions before returning an error, even if the results are not always intuitive. In this example, the value “text”
is a String
, yes, but it is also an Object
. Since the inference T = String, V = Integer
is invalid because Integer
is not a subtype of String
, the compiler uses T = Object, V = Integer
, which is valid.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论