Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is AbstractMap put() in Java?

Divine Odazie

AbstractMap.put() is a method of the Java AbstractMap class. We use it to insert a mappingkey-value pair into an AbstractMap.

Suppose the AbstractMap previously contained a mapping for a key. In this case, the old value of the mapping is replaced by the new value in the put() method. If we pass a new key-value pair, it inserts the pair as a whole.

Syntax

AbstractMap.put()

Parameters: The AbstractMap.put() method takes two parameters:

  • Key: The key to which the value of the mapping is associated with.

  • Value: The value associated with a key.

Returns: If an existing key is passed in the AbstractMap.put(), the previous value is returned. If a new key-value pair is passed, NULL is returned.

Throws: The method throws:

  • UnsupportedOperationException - if the AbstractMap does not support the put operation.

  • ClassCastException - if the class of the supplied key or value prevents it from being stored in the AbstractMap.

  • NullPointerException - if the supplied key or value is null and this AbstractMap does not permit null keys or values.

  • IllegalArgumentException - if some property of the supplied key or value prevents it from being stored in the AbstractMap.

AbstractMapDemo.java Illustration
AbstractMapDemo.java Illustration

Code

We can represent the above illustration in the code snippet below. Let’s run the code to test it:

import java.util.*;

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

        // Using the Put() method to map 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);
  
        // Inserting existing key along with new value
        String returnValue = abstractMap.put(34, "Hurrrayyyy");
        
        // Checking the return value
        System.out.println("Returned value is: " + returnValue);

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

        // Inserting a new Key-value pair
        String returnValueNewKeyValuePair = abstractMap.put(76, "MEHHHHHH");

        // Checking the return value of new Key-value pair addition
        System.out.println("Returned value is: " + returnValueNewKeyValuePair);


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

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring