java.util.Hashtable.putIfAbsent() 方法返回 null 并将指定的键与给定的值关联起来(如果指定) key 尚未与值关联(或映射为 null),否则返回当前值。
语法
public V putIfAbsent(K key, V value)
这里,K 和 V 是键和值的类型分别由容器维护。
参数
key | 指定指定值所对应的key |
value | 指定与指定键关联的值。 |
返回值
返回与指定键关联的先前值,如果该键没有映射,则返回 null。 (如果实现支持 null 值,则 null 返回还可以指示映射先前将 null 与键关联。)
异常
无。示例:
在下面的示例中,java.util.Hashtable.putIfAbsent()方法用于将键值对放入给定的哈希表中。
import java.util.*;
public class MyClass {
public static void main(String[] args) {
//创建哈希表
Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();
//填充哈希表
Htable.put(101, "John");
Htable.put(102, "Marry");
Htable.put(103, "Kim");
//打印哈希表
System.out.println("Before putIfAbsent, Htable contains: " + Htable);
//使用putIfAbsent方法
//key已经与某个值关联
//不会产生任何效果
Htable.putIfAbsent(101, "Sam");
//key 不存在于map中,因此它
//将以指定值包含在其中
Htable.putIfAbsent(104, "Jo");
//打印哈希表
System.out.println("After putIfAbsent, Htable contains: " + Htable);
}
}
上述代码的输出将是:
Before putIfAbsent, Htable contains: {103=Kim, 102=Marry, 101=John}
After putIfAbsent, Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}