HashMap Class in Java

by | Dec 20, 2020 | Java

Home » Java » HashMap Class in Java

Introduction

The HashMap class of Java implements the Map interface. Therefore, it similarly works with the key-value pair where all keys are unique. If more than one similar key is entered, the elements of the corresponding keys will be replaced. Java HashMap has the edge over other Map implementations in operations that require a key index. Some of these are updation, insertion, and deletion. The java.util package contains the HashMap class.

Unlike the TreeMap, HashMap allows only one null key and uses the parameter ‘HashMap <K, V>’ where K is the key and V is the value corresponding to that key. HashMap inherits the AbstractMap class and implements the Map interface.

HashMap Features

  • All values of the elements in a HashMap is based on the key.
  • Only unique keys are permitted in a HashMap
  • Allows only one null key but can have more than one null value as elements.
  • Non-synchronized
  • By default, the capacity of a HashMap is 16 and has a load factor of 0.75.

Declaration Syntax

public class HashMap <K,V> extends AbstractMap <K,V> implements Map <K,V>, Cloneable, Serializable

K stands for the type of keys and V stands for the element values in the HashMap.

Constructors

  • HashMap() – Creates an empty HashMap
  • HashMap (Map <? extends K,? extends V> m) – A HashMap is created using the element values of the map m.
  • HashMap (int capacity) – A HashMap of the specified capacity is created.
  • HashMap (int capacity, float loadFactor) – Creates a new HashMap with the given load factor and integer capacity.

Example

import java.util.*;
public class DemoHashMap
{
public static void main(String args[])
{
HashMap <Integer,String> map = new HashMap <Integer,String> ();
//Creating HashMap
map.put(1,"Red"); 
map.put(2,"Blue");
map.put(3,"Green");
map.put(4,"Yellow");
System.out.println("Iterating Hashmap...");
for (Map.Entry m : map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

OUTPUT

Iterating HashMap…..
1 Red
2 Blue
3 Green
4 Yellow

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author