但是,在初始化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