简体   繁体   中英

Why does new HashMap<> produce an error in JDK 1.6 but not 1.7

I noticed the following code works when compiling in eclipse with java spec 1.7 but does not work with 1.6.

HashMap<String, String> hashMap = new HashMap<>();

I'd like an explanation but this syntax and why it works for 1.7 .

The new HashMap<>() (called diamond syntax) is not allowed in JDK 1.6 simply because it was only introduced in Java SE 7.

Look for Type Inference for Generic Instance Creation in Highlights of Technology Changes in Java SE 7 .

I'd like an explanation but this syntax and why it works for 1.7 .

Here's that explanation (slightly adapted) from Oracle itself :

Compilers from releases prior to Java SE 7 are able to infer the actual type parameters of generic constructors, similar to generic methods. However, the compiler in Java SE 7 can infer the actual type parameters of the generic class being instantiated if you use the diamond ( <> ) . Consider the following example, which is valid for Java SE 7 and later:

class MyClass<X> {
  <T> MyClass(T t) {
    // ...
  }
}

MyClass<Integer> myObject = new MyClass<>("");

In this example, the compiler infers the type Integer for the formal type parameter, X , of the generic class MyClass<X> . It infers the type String for the formal type parameter, T , of the constructor of this generic class.

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):

Map<String, List<String>> myMap = new HashMap<>();

In Java SE 6 it had to be done this way:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();

More details...

因为它是JDK 1.7(Diamond运算符)的增强,所以必须在类和构造函数HashMap<String, String> hashMap = new HashMap<String, String>();上指定泛型类型HashMap<String, String> hashMap = new HashMap<String, String>();

它使用的是1.7中引入的钻石操作员

您不能使用在JDK 1.7中使用的相同语法对于JDK 1.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM