但是,在初始化Collections的特定實現時,您是否曾經想到過代碼重復? 為什么在初始化期間需要兩次寫入參數?
List<string> names = new ArrayList<string>();
Map<string, Object> objectMap = new HashMap<string, Object>();
這樣的東西。
List<string> names = new ArrayList();
Map<string, object=""> objectMap = new HashMap();
那么JDK 7中有什么新功能? 您將從新功能中獲得什么好處?
因此,首先我們需要了解原始類型和通用類型初始化之間的區別。
這樣的語句可確保實現包含初始化期間指定的相同參數。
List<string> names = new ArrayList<string>();
在以下示例中,編譯器生成未經檢查的轉換警告,因為HashMap()
構造函數引用的是HashMap
原始類型,而不是Map<String, List<String>>
類型:
Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning
鉆石算子
?
好的,現在我將介紹JDK 7的新功能。 因此,JDK 7中有一個稱為Diamond運算符的東西,它可以減少初始化時的額外鍵入。
句法:
List<string> names = new ArrayList<>();
因此,它不僅減少了您的代碼,而且確保了類型檢查。
這是一個更清晰的示例,解釋了類型推斷的好處。
高級示例:
class Demo {
void printStudentNames(List<string> names) {
for(String name:names) {
System.out.println("String name:"+name);
}
}public static void main(String[] args) {
Demo demo = new Demo();
demo.printStudentNames(new ArrayList<>()); // It saved typing here in a method call too.
List<string> names = new ArrayList<>();
printStudentNames(names);
List<string> copyOfNames = new ArrayList<>(names); // It saved typing here in a copy contructor invocation too.
}
}
現在有什么限制?
如果您使用通配符,它??將不起作用。
像這樣
Class Tree<t> {public void demoFunction(List<t> objList) {
List<t> copyOfNames = new ArrayList<t>(objList); //This is not gonna work.
}
}
在上述情況下,在復制構造函數中傳遞的參數應為Collection <? 擴展T>
因此它不會接受上述推斷類型。
參考: 為什么我們需要Java 7中的類型推斷? 來自我們的JCG合作伙伴 Saurab Parakh在Coding is Cool博客上。
翻譯自: https://www.javacodegeeks.com/2012/05/type-inference-from-java-7.html