Thursday , May 25 2017
Home / java / How HashMap Works In Java

How HashMap Works In Java

HashMap is one of the most important Map implementation class in Collections framework. And is also important for interview. Lets understand in detail.

What is a Map?

Map provide a way to store key/value pairs. In Java, a map is an object that contains key/value associations. While both keys and values are objects, keys must be unique whereas values need not be unique. Keys are used to identify and retrieve values from a map.

Java provides the functionality to work with maps through the Map interface. The get () and put () methods in the Map interface are used to retrieve a value from a map and to store a value into a map respectively.

The HashMap Class

In Java, the HashMap class stores maps in hash tables. HashMap is a generic class that implements the Map interface and has the following declaration:

class HashMap<K,V>

In this declaration, K indicates the type of keys and V indicates the type of values in the map.

Example:

HashMap<String, Float> hm = new HashMap<String, Float>();

The HashMap class allows the use of null values and null keys. It is unsynchronized and the order of the map in a hash table does not remain constant. The HashMap class uses the hashCode() method as its hash function.

A HashMap instance has two parameters, namely, initial capacity and load factor.

Initial capacity: is the capacity of the HashMap instance at the time of creation. It denotes the number of buckets assigned to the hash table for data storage.

Load factor: specifies the maximum limit of the hash map at which the current capacity of the hash table needs to be increased.

The default initial capacity and load factor of a HashMap instance are 16 and 0.75 respectively. While creating a HashMap instance, you can either specify values for the initial capacity and load factor or allow Java to use the default values.

The automatic mechanism that increases the capacity of a hash map is called rehashing. The initial capacity and load factor are important because too many rehash operations affect the performance of the hash map. Therefore, care must be taken to set optimal initial capacity and load factor.

Note: The HashMap class provides constant-time performance for the get and put operations. If its granted that the hash function stores the elements evenly across buckets, the time complexity of the operations in a HashMap instance is O(1).

Key points

  1. HashMap is fast.
  2. HashMap accepts the null.
  3. HashMap stores key along with the value pairs.
  4. Easy to use the HashMap functionality.
  5. Easy for looking the code on the Open JDK or Java source.
  6. HashMap works on the principle of hashing.
  7. We can get(key) method and put(key, value) to store and retrieve Objects from the HashMap.
  8. When passing the Key as well as the Value object.
  9. To put() method for the Java HashMap, then the HashMap can also give the calls hashCode method for the Key object.
  10. Storing the Entry object that can be useful for the bucket location and the HashMap can be useful for the key and value object along with the Map.Entry.

constructors in HashMap class:

Constructor
Constructs

HashMap()

A default hash map with 16 as the initial capacity and 0.75 as the load factor.

HashMap(Map<? extends K, ? extends V>m)

A hash map with the mappings specified by Map and initializes it using the elements of m.

HashMap(int initialCapacity)

A hash map with the initial capacity specified by the initialCapacity parameter and 0.75 load factor.

HashMap(int initialCapacity, float loadFactor)

A hash map with the initial capacity specified by the initialCapacity parameter and the load factor specified by the loadFactor parameter.

Example

The following program is an example that uses a HashMap instance to store customer names and account balance information.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapExample {

    public static void main(String args[]) {
        HashMap<String, Double> hm = new HashMap<String, Double>();

        hm.put("Jason Smith", new Double(2325.34));
        hm.put("Joey Williams", new Double(553.52));
        hm.put("Angelina Johnson", new Double(658.25));
        hm.put("Tedd Wilson", new Double(100.50));
        hm.put("Katherine Hunt", new Double(-18.28));

        Set<Map.Entry<String, Double>> set = hm.entrySet();
        for (Map.Entry<String, Double> me : set) {
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        System.out.println();

        double balance = hm.get("Angelina Johnson");
        hm.put("Angelina Johnson", balance + 500);
        System.out.println("Angelina Johnson's new balance: "
                + hm.get("Angelina Johnson"));
    }
}

Jason Smith: 2325.34
Angelina Johnson: 658.25
Tedd Wilson: 100.5
Katherine Hunt: -18.28
Joey Williams: 553.52

Angelina Johnson’s new balance: 1158.25

In this example, hm is a HashMap instance that stores customer name and account balance as a key/value pair of string and double values. By using the put() method, the keys and values are stored into the hash map.

The entrySet() method is used to obtain a set-view of the hash map. The result of this method is a set of elements that contain the HashMap entries. Here entry represents the key and value.

Each element in this set is an object of the Map.Entry interface. The program uses a for each loop with the getKey() and getValues() methods to display all the map entries and then updates the value in Angelina Johnson’s account.

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Binary Literals Java 7 Example Tutorials

Binary literals is one of the new feature added in Java 7. We already know …

Leave a Reply

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