用织梦做的企业网站,入口网站推广,电子商务网站建设源码,广州网站设计素材每个优秀的程序员都喜欢编写简洁但有效且经过优化的代码。 类型推断是JDK 7中引入的一种方法#xff0c;它肯定会为您带来更少键入的好处。 您以以下方式使用Java代码已有很长时间了。 但是#xff0c;在初始化Collections的特定实现时#xff0c;您是否曾经想到过代码重复它肯定会为您带来更少键入的好处。 您以以下方式使用Java代码已有很长时间了。 但是在初始化Collections的特定实现时您是否曾经想到过代码重复 为什么在初始化期间需要两次写入参数 Liststring names new ArrayListstring();
Mapstring, Object objectMap new HashMapstring, Object(); 现在大多数人都将考虑像在以前的JDK版本中一样将其初始化为原始类型。 这样的东西。 Liststring names new ArrayList();
Mapstring, object objectMap new HashMap(); 那么JDK 7中有什么新功能 您将从新功能中获得什么好处 因此首先我们需要了解原始类型和通用类型初始化之间的区别。 这样的语句可确保实现包含初始化期间指定的相同参数。 Liststring names new ArrayListstring(); 在以下示例中编译器生成未经检查的转换警告因为HashMap()构造函数引用的是HashMap原始类型而不是MapString, ListString类型 MapString, ListString myMap new HashMap(); // unchecked conversion warning 钻石算子 好的现在我将介绍JDK 7的新功能。 因此JDK 7中有一个称为Diamond运算符的东西它可以减少初始化时的额外键入。 句法 Liststring names new ArrayList(); 因此它不仅减少了您的代码而且确保了类型检查。 这是一个更清晰的示例解释了类型推断的好处。 高级示例 class Demo {
void printStudentNames(Liststring 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.
Liststring names new ArrayList();
printStudentNames(names);
Liststring copyOfNames new ArrayList(names); // It saved typing here in a copy contructor invocation too.
}
} 现在有什么限制 如果您使用通配符它将不起作用。 像这样 Class Treet {public void demoFunction(Listt objList) {
Listt copyOfNames new ArrayListt(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