问题描述
我的一个朋友注意到
var<Integer> list = new ArrayList<Double>();
在Java中有效.事实证明,将 list
的类型评估为 ArrayList< Double>
.
was valid in Java. It turns out that the type of list
is evaluated to ArrayList<Double>
.
使用 var< Integer>时list = new ArrayList<>();
, list
只是 ArrayList< Object>
.
我们两个人都无法弄清 var
的通用类型是做什么的,因为它似乎被忽略了.但是,如果是这样,为什么这在语法上甚至是正确的呢?
Both of us were not able to figure out, what the generic type of var
does, as it seems to be ignored. But if so, why is this even syntactically correct in the first place?
推荐答案
这确实是一个错误,但证明位于 Java语言规范§14.4局部变量声明语句:
This is indeed a bug, but the proof lies in the Java Language Specification § 14.4 Local Variable Declaration Statements:
LocalVariableType:
UnannType
var
您可以看到广告,其中列出了受限标识符 var
,没有任何其他标记.同样, UnannType
最终解析为令牌 TypeIdentifier
,该令牌明确禁止 var
.
Ad you can see, the restricted identifier var
is listed without any other token. Also, UnannType
eventually resolves to the token TypeIdentifier
which explicitly forbids var
.
因此, var< Integer>
无效无效.
这篇关于var T是什么?用Java做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!