HashMap<Character, Integer> alphabet1 = new HashMap(); // (1)
(1) initializes a HashMap
without using generics but uses an unsafe cast to a HashMap
with generics afterwards. This should raise a compiler warning.
HashMap<Character, Integer> alphabet1 = new HashMap<Character, Integer>(); // (2)
(2) Initializes a HashMap
with generics and declares a variable of the type HashMap
with generics. It can be shorthanded to
HashMap<Character, Integer> alphabet1 = new HashMap<>(); // (2b)
Here, the compiler uses type inference to infer the genrics of the HashMap
from the declaration of the left hand side.
HashMap alphabet1 = new HashMap<Character, Integer>(); // (3)
(3) Initialzes a HashMap with generics, but the variable alphabet1
does not reuse the generics information. Thus, you can not access the methods on this HashMap
value in a generic manner (e.g., you will get a value cast to an java.lang.Object
when calling alphabet1.get('a')
and not cast to an Integer
).
Map alphabet1 = new HashMap<Character, Integer>(); // (4)
(4) is similar to (3) but here, the alphabet1
is typed with Map
instead of HashMap
. Thus, you cannot access methods being defined in HashMap
but not in its super interface Map
.
HashMap alphabet1 = new HashMap(); // (5)
(5) is similar to (3), it does not use generics for initializing the HashMap
.
Map alphabet1 = new HashMap(); // (6)
(6) is similar to (4) and does not use generics for initializing the HashMap
.