HashMap size() Method in Java

Published by user on

The size() method of HashMap returns the number of key-value entries present in the map. When we create the HashMap its size is zero.

This size of the HashMap increases as we add key-value pairs and reduce as we remove the entries.

After clearing the HashMap the size again becomes zero. You cannot directly set the size of the HashMap.

Method Signature

public int size()

Parameters

It does not accept any parameter.

Program

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

// This program shows
// how to use size() method
// to get the number of entries in the map
public class HashMapSize {
        public static void main(String[] args) {
                // Create an instance of HashMap
                Map map = new HashMap();
                // Add entries to the HashMap
                map.put(101, "John");
                map.put(102, "Adam");
                map.put(103, "Ricky");
                map.put(104, "Chris");

                // Print entries in Map
                System.out.println("Map elements : " + map);
                // Print size of the map
                System.out.println("Size of HashMap : " + map.size());
                // Remove entry with key 101
                System.out.println("Removed entry with key 101 and value : " + map.remove(101));
                // Size of the map after removing entry
                System.out.println("Size of HashMap after removing 101 : " + map.size());
                // Clear the HashMap
                map.clear();
                System.out.println("Size of HashMap after clearing : " + map.size());
        }
}

Output

Map elements : {101=John, 102=Adam, 103=Ricky, 104=Chris}
Size of HashMap : 4
Removed entry with key 101 and value : John
Size of HashMap after removing 101 : 3
Size of HashMap after clearing : 0

Explanation

  1. Create an instance of HashMap
  2. Add 4 entries to it
  3. Use the size() method to get the size, i.e. four in our case
  4. Remove the entry using the remove() method, size should reduce to 3 now
  5. Clear the HashMap, size should be equal to 0 now
Categories: Java

0 Comments

Leave a Reply

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