Different Ways of Creating HashMaps

67,612

Solution 1

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();

Solution 2

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>();

Solution 3

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.

Solution 4

- 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();

Share:
67,612
StaticGamedude
Author by

StaticGamedude

Updated on July 09, 2022

Comments

  • StaticGamedude
    StaticGamedude almost 2 years

    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 = new HashMap();
    

    vs

    HashMap<,>hash1 = new HashMap <,> (); //Filled in with whatever Key and Value you want. 
    

    I thought when you define a HashMap it requires the Key and Value. Any help would be much appreciated. Thank You.

  • HericDenis
    HericDenis over 11 years
    +1 for good explanation about compile-time and run-time differences.
  • HericDenis
    HericDenis over 11 years
    you're welcome @StaticGamedude , could you please consider mark it as the answer? That check mark under the helpful votes :)