仅当此HashMap实例中不存在这样的映射时,才使用HashMap类的putIfAbsent(K key,V value)方法来映射具有指定值的指定键。
用法:
public V putIfAbsent(K key, V value)
参数:此方法接受两个参数:
key:这是必须映射提供的值的键。
value:如果不存在,则为必须与提供的键相关联的值。
返回值:此方法返回null(如果之前没有与提供的键的映射,或者已映射为null值)或与提供的键关联的先前值。
异常:此方法引发以下异常:
IllegalArgumentException:如果指定的键或值阻止其存储在Map中。
程序1:
// Java program to demonstrate
// putIfAbsent(Key, value) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a HashMap and add some values
HashMap map
= new HashMap<>();
map.put("a", 10000);
map.put("b", 55000);
map.put("c", 44300);
map.put("e", 53200);
// print original map
System.out.println("HashMap:\n "
+ map.toString());
// put a new value which is not mapped
// before in map
map.putIfAbsent("d", 77633);
// print newly mapped map
System.out.println("New HashMap:\n "
+ map);
}
}
输出:
HashMap:
{a=10000, b=55000, c=44300, e=53200}
New HashMap:
{a=10000, b=55000, c=44300, d=77633, e=53200}
程序2:
// Java program to demonstrate
// putIfAbsent(Key, value) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a HashMap and add some values
HashMap map
= new HashMap<>();
map.put("a", 10000);
map.put("b", 55000);
map.put("c", 44300);
map.put("e", null);
// print original map
System.out.println("HashMap:\n "
+ map.toString());
// put a new value which is not mapped
// before in map and store the returned
// value in r1
Integer r1 = map.putIfAbsent("d", 77633);
// put a new value for key 'e' which is mapped
// with a null value, and store the returned
// value in r2
Integer r2 = map.putIfAbsent("e", 77633);
// print the value of r1
System.out.println("Value of r1:\n " + r1);
// print the value of r2
System.out.println("Value of r2:\n " + r2);
// print newly mapped map
System.out.println("New HashMap:\n "
+ map);
}
}
输出:
HashMap:
{a=10000, b=55000, c=44300, e=null}
Value of r1:
null
Value of r2:
null
New HashMap:
{a=10000, b=55000, c=44300, d=77633, e=77633}