java語法糖--型別推導/型別推斷(type inference)
先看如下兩個例子
1. 泛型
在Java7以前的版本中使用泛型型別,需要在宣告并賦值的時候,兩側都加上泛型型別
List<User> userList = new ArrayList<User>();
在java7及java7之后,使用泛型可以簡寫為
List<User> userList = new ArrayList<>();
2. java8中,lambda運算式引數串列的引數型別可以省略不寫
List<Integer> list= 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 static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); }
一直沒真正搞明白 呼叫這個Lists#newArrayList 與 直接呼叫 new ArrayList<>的區別,后來下載原始碼,看到這個方法的注釋棒棒噠,
/** * Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and earlier). * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableList#of()} instead. * * <p><b>Note for Java 7 and later:</b> 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 <a href="https://www.cnblogs.com/buguge/p/http://goo.gl/iz2Wi">"diamond" syntax</a>. */ @GwtCompatible(serializable = true) public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); }
Note for Java 7 and later:</b> 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 <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.-----注意:如果你在使用Java7及之后的版本,大可不用這個方法,可以直接使用ArrayList#ArrayList()構造器來取而代之,發揮java7的“diamond”語法優勢,
這里的diamond語法指的就是型別推導,
其實,再說這個Lists#newArrayList,我覺得它存在的另一重意義是:java不建議我們在程式里直接去new物件,而是封裝這種new物件的程序,然后程式里呼叫這種封裝的方法,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/421298.html
標籤:Java
上一篇:動力節點-王媽媽Springboot教程(四)ORM 操作 MySQL
下一篇:跨域
