Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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 .

like image 552
Menelaos Avatar asked May 17 '13 14:05

Menelaos


People also ask

What does HashMap return if key does not exist?

If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.

How HashMap works internally in Java journaldev?

How HashMap works in java? HashMap in java use it's inner class Node<K,V> for storing mappings. HashMap works on hashing algorithm and uses hashCode() and equals() method on key for get and put operations. HashMap use singly linked list to store elements, these are called bins or buckets.

Where is HashMap stored in Java?

HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value.


3 Answers

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.

like image 167
acdcjunior Avatar answered Oct 16 '22 00:10

acdcjunior


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...

like image 14
Adam Siemion Avatar answered Oct 16 '22 00:10

Adam Siemion


Because it's an enhancement of JDK 1.7 (the Diamond operator), before you have to specify the Generic types on the class and on the constructor HashMap<String, String> hashMap = new HashMap<String, String>();

like image 4
gma Avatar answered Oct 15 '22 23:10

gma