Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between jdk7 & jdk8 in Generic?

Tags:

java

List<String> box = new ArrayList<>();
box.add("small");
box.addAll(new ArrayList<>());

in jdk7 box.addAll(new ArrayList<>()) will not compiled, but in jdk8 is will

anyone can give me a help to understand what's the difference between jdk7 & jdk8 in Generic?

like image 766
huang botao Avatar asked Dec 17 '22 14:12

huang botao


1 Answers

The difference is that Java 8 introduced polyexpressions.

These are expressions whose type is left somewhat undetermined, but is determined by context of how the expression is used.

new ArrayList<>() is a polyexpression. On its own, it could be a list with any element type: the compiler "waits and sees" before it decides on the type.

Java 7 didn't support polyexpressions. It would consider new ArrayList<>() to be new ArrayList<Object>(), and thus incompatible with box.addAll.

Without polyexpressions, lambdas and streams would have been incredibly awkward.

like image 72
Andy Turner Avatar answered Jan 11 '23 19:01

Andy Turner