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 .
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 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.
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.
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 classMyClass<X>
. It infers the typeString
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...
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With