Java Hashtable putIfAbsent()方法及示例
HashTable类的 putIfAbsent(Key, value) 方法允许将一个值映射到一个给定的键上,如果给定的键没有与一个值相关联或者被映射为空。如果HashMap中已经存在这样的键值集,则返回一个空值。
语法
public V putIfAbsent(K key, V value)
参数: 该方法接受两个参数。
- key : 如果key不与任何值相关联,则指定值将被映射到该键上。
- value :指定将被映射到指定的键的值。
返回: 该方法返回 映射到键的现有值, 如果以前没有值映射到该键, 则返回null 。
异常: 这个方法会抛出。
- NullPointerException :当指定参数为空时。
下面的程序说明了putIfAbsent(Key, value)方法。
程序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 table and add some values
Map<String, Integer>
table = new Hashtable<>();
table.put("Pen", 10);
table.put("Book", 500);
table.put("Clothes", 400);
table.put("Mobile", 5000);
// print map details
System.out.println("hashTable: "
+ table.toString());
// Inserting non-existing key with value
// using putIfAbsent method
String retValue
= String.valueOf(table
.putIfAbsent("Booklet", 2500));
// Print the returned value
System.out.println("Returned value "
+ "for Key 'Booklet' is: "
+ retValue);
// print new mapping
System.out.println("hashTable: "
+ table);
// Inserting existing key with value
// using putIfAbsent method
retValue
= String.valueOf(table
.putIfAbsent("Book", 4500));
// Print the returned value
System.out.println("Returned value"
+ " for key 'Book' is: "
+ retValue);
// print new mapping
System.out.println("hashTable: "
+ table);
}
}
输出。
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400}
Returned value for Key 'Booklet' is: null
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400, Booklet=2500}
Returned value for key 'Book' is: 500
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400, Booklet=2500}
程序2: 显示NullPointerException
// Java program to demonstrate
// putIfAbsent(key, value) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a table and add some values
Map<Integer, String>
table = new Hashtable<>();
table.put(1, "100RS");
table.put(2, "500RS");
table.put(3, "1000RS");
// print map details
System.out.println("hashTable: "
+ table.toString());
try {
table.putIfAbsent(null, "8");
}
catch (NullPointerException e) {
System.out.println("Exception: " + e);
}
}
}
输出。
hashTable: {3=1000RS, 2=500RS, 1=100RS}
Exception: java.lang.NullPointerException
参考文献: https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html#putIfAbsent-K-V-