The diamond operator, which you should have been familiar with from its introduction in Java7, is probably incompatible with
var. It tells the compiler to use the same actual type parameter as in the declaration, and
var hasn't got a declared type. If you look at this example I ran on JShell, you will see it compiles without warning, but there is no type‑safety at all. The
javac tool seems to interpret
var as plain simple
List, without using generics, so I suggest you should avoid
var like the plague.
Campbell's JShell wrote:jshell
| Welcome to JShell -- Version 23.0.1
| For an introduction type: /help intro
jshell> void foo()
...> {
...> var list = new ArrayList<>();
...> }
| created method foo()
jshell> void foo()
...> {
...> var list = new ArrayList<>(); list.add("Campbell"); list.add(123); System.out.println(list);
...> }
| modified method foo()
jshell> foo()
[Campbell, 123]
jshell>
If you change the declaration to
List<XYZ>, where XYZ is any “real” type other than Object, you will get type‑safety back, and you will see whether you can get the code to compile at all.
Let's see what the
JLS (=Java® Language Specification) says about types of variables. I don't think that is the correct section for generics.
Remember you can only use
var for local variables. You often see generic declarations for parameters
The following declaration would be legal and maintain type‑safety:-