Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is AbstractMap clear() in Java?

Divine Odazie

AbstractMap.clear() is a method of the Java AbstractMap class. We use it to remove all of the mappings from an AbstractMap. The AbstractMap will become empty after we call this method.

Syntax

AbstractMap.clear()

The AbstractMap.clear() takes no parameter and doesn’t return any valuei.e., void.

The method throws an UnsupportedOperationException error if the AbstractMap does not support the clear() operation.

AbstractMapDemo.java illustration
AbstractMapDemo.java illustration

Code

We can see what’s illustrated above in the code below.

import java.util.*;

class AbstractMapDemo {
    public static void main(String[] args)
    {
  
        // Creating an AbstractMap
        AbstractMap<Integer, String>
            abstractMap = new HashMap<Integer, String>();

        // Mapping string values to int keys
        abstractMap.put(21, "Shot");
        abstractMap.put(42, "Java");
        abstractMap.put(34, "Yaaaayy");
    
        // Printing the AbstractMap
        System.out.println("The Mappings are: "
                           + abstractMap);
  
        // Clearing the AbstractMap using clear() method
        abstractMap.clear();

        // Printing the final AbstractMap
        System.out.println("The Final Mappings are: "
                           + abstractMap);
  
        
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring