I\'ve been learning about HashMaps recently but I have one question that I can\'t seem to get a clear answer on. The main difference between -
HashMap hash1
Specifying the key
and the value
types allows for greater type-safety by enabling compile-time typing enforcement.
This makes it easier to write code that doesn't accidentally mix up the key and value types, and reduces the amount of casts that you must explicitly declare in the code.
However, it is important to be aware the these type-checks are compile-time only, i.e. once the application is running, the JVM will allow you to use any types for the keys and values.
- Generics
can be implied to classes, interfaces, methods, variables etc.. but the most important reason for which its used is making the Collection
more type safe.
- Generics
make sure that only specific type of object enters and comes out of the Collections
.
- Moreover its worth mentioning that there is a process known as Erasure
,
-> Erasure
is a process where the type parameters
and type arguments
are removed from the generic classes and interfaces by the compiler, making it back compatible with the codes that where written without Generics.
So,
HashMap<String, Integer> map = new HashMap<String, Integer>();
becomes of Raw type
,
HashMap map = new HashMap();
You should take a look on Java generics, if you don't specify the types of the HashMap, both key and value will be Object
type.
So, if you want a HashMap with Integer
keys and String
values for instance:
HashMap<Integer, String> hashMap= new HashMap<Integer, String>();
Those are the options you have:
J2SE <5.0 style:
Map map = new HashMap();
J2SE 5.0+ style (use of generics):
Map<KeyType, ValueType> map = new HashMap<KeyType, ValueType>();
Google Guava style (shorter and more flexible):
Map<KeyType, ValueType> map = Maps.newHashMap();