HashMap in Java

In Java, HashMap is the implementation of the Map interface. HashMap offers various options to store and retrieve key-value pairs, where each unique key maps to a specific value.

HashMap Properties

  • Underline data structure is HashTable.
  • Duplicate keys are not allowed but duplicate values are allowed.
  • Insertion order is not preserved.
  • Heterogeneous objects are allowed.
  • Null is allowed for key only once.
  • Null is allowed for values any number of times.
  • HashMap implements Map, Cloneable, and Serializable interfaces.
  • HashMap is the best choice if our frequent operation is a search operation.

HashMap Constructor

HashMap()

 HashMap map = new HashMap();

This constructor creates an empty HashMap object with a default initial capacity of 16 and a default load factor fill ratio of 0.75

HashMap(int initialCapacity )

public HashMap(     @Range(from = 0, to = Integer.MAX_VALUE)  int initialCapacity )

This constructor creates an empty HashMap object with the specified initial capacity and the default load factor / fill ration (0.75)

HashMap(int initialCapacity, float loadFactor )

public HashMap(     @Range(from = 0, to = Integer.MAX_VALUE)  int initialCapacity,
    float loadFactor )

This constructor creates an empty HashMap object with the specified initial capacity and load factor/ fill ratio.

HashMap Java Implementation

package thecodedata;

import java.util.HashMap;

public class HashMapDemo {

    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(1, "The");
        map.put(2, "Code");
        map.put(3, "Data");
        //Printing HashMap
        System.out.println(map);
        map.put(3, "Java");
        System.out.println(map.get(3));
        map.remove(3);
        System.out.println(map);
    }}
implementation of hashmap in java

Difference Between HashMap and HashTable

HashMapHashTable
All methods are non- synchronizedAll methods are synchronized
Not thread safethread safe
Performance is highPerformance is low
Null is allowed for both key and valueNull is not allowed for key and value
Introduced in Java 1.2vIntroduced in Java 1.0v

Similar Java Tutorials

Leave a Comment