![]() |
VOOZH | about |
The put() method in ConcurrentHashMap class in Java is used to associate a given value with a given key in the map. It has the following signature:
V put(K key, V value)
where:
When a put() operation is performed, the method first acquires the lock on the segment of the map corresponding to the given key. If the key is already present in the map, the old value associated with the key is replaced by the new value. If the key is not present in the map, a new entry is added with the given key-value pair.
The put() method returns the previous value associated with the given key, or null if there was no previous mapping for the key. If you don't need the previous value, you can simply ignore the return value.
{Bob=30, Alice=25, Charlie=35}
Old value for Bob: 30
{Bob=40, Alice=25, Charlie=35}
New value for Dave: null
{Bob=40, Alice=25, Charlie=35, Dave=45}
The put() method of the class ConcurrentHashmap in Java is used to insert a mapping into this map. It takes the parameter as a (Key, Value) pair. If an existing key is passed with a value, then this method updates the value of that key. Else if a new pair is passed, then the pair gets inserted as a whole.
Syntax:
public V put(K key, V value)
Parameters: This method accepts two mandatory parameters:
Return Value: This method returns the previous value associated with key, or null if there was no mapping for key.
Exception: This method throws NullPointerException if the specified key or value is null Below is the example to illustrate put() method:
Program 1: When the Key, Value passed is new.
{1=1, 2=1, 3=1, 4=1, 5=1, 6=1}Program 2: When an existing Key, Value is passed.
Map: {Geek=100}
Returned Value: null
Map: {Geek=200}
Returned Value: 100
Map: {Geek=300}
Returned Value: 200
Map: {Geek=400}
Returned Value: 300
Map: {Geek=500}
Returned Value: 400
{Geek=500}Program 3: To demonstrate NullPointerException
{1=1, 2=1, 3=1, 4=1, 5=1, 6=1}
When (null, "10") is passed as parameter:
Exception: java.lang.NullPointerException
When ("10", null) is passed as parameter:
Exception: java.lang.NullPointerException