4

Let's take a look at these declarations:

ArrayList<String> list = new ArrayList<String>() {{add("hi");}};
System.out.println(list.get(0));

and

var list = new ArrayList<String>() {{add("hi");}};
System.out.println(list.get(0));

Both are identical, thanks to type inference. But I was shocked to see these compile as well:

var<String> list = new ArrayList<String>() {{add("hi");}};
System.out.println(list.get(0));

and

var<Integer> list = new ArrayList<String>() {{add("hi");}};
System.out.println(list.get(0));

The same byte code is generated by all of the above approaches. I was expecting var<T> to fail but it doesn't. I have searched for this in the JLS and JVMS but didn't find anything related to this behaviour.

Why does Java think var<T> is valid? Backwards compatibility?

EDIT: See comments.

Boann
  • 48,794
  • 16
  • 117
  • 146
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67

0 Answers0