What does var<T> do in Java?

不羁岁月 提交于 2020-06-08 16:56:51

问题


A friend of mine noticed that

var<Integer> list = new ArrayList<Double>();

was valid in Java. It turns out that the type of list is evaluated to ArrayList<Double>.

When using var<Integer> list = new ArrayList<>();, list is just ArrayList<Object>.

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?


回答1:


This is indeed a bug, but the proof lies in the Java Language Specification § 14.4 Local Variable Declaration Statements:

LocalVariableType:
    UnannType
    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.

So no, var<Integer> is not valid.




回答2:


As it turns out, the usage of var<T> is only allowed in Eclipse with JDT core, javac does not accept this. Therefore, I assume this is a bug in Eclipse.

EDIT: As @MC Emperor showed, this is definitely a bug. I have added this bug to the Eclipse Bugzilla.



来源:https://stackoverflow.com/questions/60330699/what-does-vart-do-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!