AbstractMap.put()
is a method of the Java AbstractMap class. We use it to insert a
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.
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.
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 AbstractMapAbstractMap<Integer, String>abstractMap = new HashMap<Integer, String>();// Using the Put() method to map string values to int keysabstractMap.put(21, "Shot");abstractMap.put(42, "Java");abstractMap.put(34, "Yaaaayy");// Printing the AbstractMapSystem.out.println("The Mappings are: "+ abstractMap);// Inserting existing key along with new valueString returnValue = abstractMap.put(34, "Hurrrayyyy");// Checking the return valueSystem.out.println("Returned value is: " + returnValue);// Printing the current AbstractMapSystem.out.println("The current Mappings are: "+ abstractMap);// Inserting a new Key-value pairString returnValueNewKeyValuePair = abstractMap.put(76, "MEHHHHHH");// Checking the return value of new Key-value pair additionSystem.out.println("Returned value is: " + returnValueNewKeyValuePair);// Printing the final AbstractMapSystem.out.println("The Final Mappings are: "+ abstractMap);}}