·  JAVA – Syntax – Variables – Collections – HashMap

 

- Info:

  - Hashmap is structure contining key-value pairs.

  - Hashmap can't contain duplicate keys.

  - Both keys and values can be any Object, Primitive Type or null value.

 

- Use HashMap instead Hashtables:

  - it allows null values for key and values,

  - it's iterator is fail-safe throwing Exception if another thread tries to modify collection "structurally" while iterating.

  - it is not thread-safe making it faster and giving you an option to synchronize it or not.

 

- Procedure:

  - Create JAVA Console Application Test.java

 

    Test.java

    import java.util.HashMap;

   

    public class Test {

      

      public static void main (String arg[]) throws Exception {

        

        //PUT ELEMENTS.-------------------------------------------

        HashMap   hashmap         = new HashMap();

                  hashmap.put("key"           , "element"          ); //Add key-value pair.

                  hashmap.put("age"           , 33                 );

                  hashmap.put(new Integer(34) , false              );

                  hashmap.put(1               , new Character('A') );

      

        //GET ELEMENTS.-------------------------------------------             

        String    name            =   (String   ) hashmap.get ("key"           );

        int       age             = ( (Integer  ) hashmap.get ("age"           ) ).intValue     ();

        boolean   flag            = ( (Boolean  ) hashmap.get (new Integer(34) ) ).booleanValue ();

        char      stuff           = ( (Character) hashmap.get (1               ) ).charValue    ();

        

        //STATISTICS.---------------------------------------------

        boolean   containsElement = hashmap.containsValue("element"); 

        boolean   containsKey     = hashmap.containsKey  ("key"    ); 

   

        boolean   isEmpty         = hashmap.isEmpty      (         );      

        int       size            = hashmap.size         (         );                     

   

        String    removed = (String) hashmap.remove       ("key"    );  

                                     hashmap.clear        (         );                       

   

        //DISPLAY STATISTICS.-------------------------------------

        System.out.println ("Contains 'element' = " + containsElement);

        System.out.println ("isEmpty            = " + isEmpty        );

        System.out.println ("size               = " + size           );

        System.out.println ("removed element    = " + removed        );

            

      }

      

    }