putIfAbsent(K, V): This method is available in java.util.WeakHashMap class of Java.
Syntax:
V java.util.Map.putIfAbsent(K key, V value)
This method takes two arguments. If the specified key is not already associated with a value associated with the given value and returns null, else returns the current value.
Parameters: Two parameters are required for this method.
key: key with which the specified value is to be associated.
value: value to be associated with the specified key.
Returns: the previous value associated with the specified key, or null if there was no mapping for the key.
Throws:
1. UnsupportedOperationException - if the put operation is not supported by this map.
2. ClassCastException - if the key or value is of an inappropriate type for this map.
3. NullPointerException - if the specified key or value is null, and this map does not permit null keys or values.
4. IllegalArgumentException - if some property of the specified key or value prevents it from being stored in this map.
Approach
Java
import java.util.WeakHashMap;public class WeakHashMapputIfAbsent {public static void main(String[] args) {WeakHashMap<String, Integer> weakHashMap =new WeakHashMap<String, Integer>();weakHashMap.put("Java", 1);weakHashMap.put("Hello", 2);String key = "C++";Integer value = 3;System.out.println(weakHashMap.putIfAbsent(key, value));}}
Output:
null
No comments:
Post a Comment