java语法糖--类型推导/类型推断(type inference)
java语法糖--类型推导/类型推断(type inference)
先看如下两个例子
1. 泛型
在Java7以前的版本中使用泛型类型,需要在声明并赋值的时候,两侧都加上泛型类型
ListuserList = new ArrayList ();
在java7及java7之后,使用泛型可以简写为
ListuserList = new ArrayList<>();
2. java8中,lambda表达式参数列表的参数类型可以省略不写
Listlist= Arrays.asList(1,2,3); list.stream().forEach(i-> System.out.println(i));
以上就是java7之后并在java8发扬光大的java语法糖————类型推断,又叫类型推导,type inference。就是说,我们无需在实例化时(new子句中)显式指定类型,编译器会根据声明子句自动推导出来实际类型。
就像上面的泛型声明一样,编译器会根据变量声明时的泛型类型自动推断出实例化List时的泛型类型。再次提醒一定要注意new ArrayList后面的“<>”,只有加上这个“<>”才表示是自动类型推断,否则就是非泛型类型的ArrayList,并且在使用编译器编译源代码时会给出一个警告提示(unchecked conversion warning)。这一对尖括号"<>"官方文档中叫做"diamond"。
基于此,我暗暗看了一下compile后的.class代码。发现也没什么改变~~~
com.google.common.collect.Lists#newArrayList
guava工具包里com.google.common.collect.Lists有如下返回空List的方法
@GwtCompatible(serializable = true) public staticArrayList newArrayList() { return new ArrayList (); }
一直没真正搞明白 调用这个Lists#newArrayList 与 直接调用 new ArrayList<>的区别。后来下载源码,看到这个方法的注释棒棒哒。
/** * Creates a mutable, empty {@code ArrayList} instance (for Java 6 and earlier). * *Note: if mutability is not required, use {
@link ImmutableList#of()} instead. * *Note for Java 7 and later: this method is now unnecessary and * should be treated as deprecated. Instead, use the {
@code ArrayList} * {@linkplain ArrayList#ArrayList() constructor} directly, taking advantage * of the new http://goo.gl/iz2Wi">"diamond" syntax. */ @GwtCompatible(serializable = true) public staticArrayList newArrayList() { return new ArrayList (); }
Note for Java 7 and later: this method is now unnecessary and should be treated as deprecated. Instead, use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor} directly, taking advantage of the new "diamond" syntax.-----注意:如果你在使用Java7及之后的版本,大可不用这个方法,可以直接使用ArrayList#ArrayList()构造器来取而代之,发挥java7的“diamond”语法优势。
这里的diamond语法指的就是类型推导。
其实,再说这个Lists#newArrayList,我觉得它存在的另一重意义是:java不建议我们在程序里直接去new对象,而是封装这种new对象的过程,然后程序里调用这种封装的方法。