HashMap Iteration Add Get Clone Java

HashMap Iteration Add Get Clone Java

Three programs are given on HashMap with different functionalities used very often in coding.

  1. HashMap General: In this program, API and the general operations like adding, retrieving and deleting elements, size and checking the existence of elements are done.
  2. HashMap Iteration: The iteration styles of elements, adding elements of one HashMap to another and cloning are shown.
  3. HashMap Sort: Sorting operations on keys and values are done. Special attention is paid to retrieve the key when a value is given.

Note: It is advised to read the tutorial on HashMap before attempting the above programs as it gives the knowledge on features, methods and super classes of HashMap etc.

It is the second program of the above three.

Example on HashMap Iteration Add Get Clone

HashMap Iteration Add Get Clone
Output screen on HashMap Iteration Add Get Clone

A generics HashMap object hm1 is created that stores keys as strings and values as integers. With put() method elements are added.

With HashMap, Iterator cannot be used as Iterator stores elements of single entities but HashMap stores pairs. The new JDK 1.5 enhanced for loop (foreach) cannot be used straight away for the same reason. It is used indirectly. The keySet() returns all the keys of HashMap hm1. As keys are single entities, to iterate them, foreach loop is used. The str refers a key and using the key str, the value associated is retrieved with get() method.

Another generics object hm2 is created and all the elements of hm1 are added at a time with putAll() method. equals() method is used to check both hm1 and hm2 contains the same elements are not. As they have same, the method returns true.

Any Collection object including HashMap can be cloned. As the cloned object, hm3 and the hm1 occupy different locations and have their own set of values, they maintain perfect encapsulation.

Leave a Reply

Your email address will not be published. Required fields are marked *