Java 字典 remove()方法
Dictionary类的 remove() 方法接受一个键作为参数,并删除映射到该键的相应值。
语法
public abstract V remove(Object key)
参数: 该函数接受一个参数 key ,表示要从 dictionary 中删除的 key 及其映射。
返回值: 该函数返回映射到 该键 的值,如果 该键 没有映射,则返回 NULL。
异常: 如果作为参数传递的 key 是NULL,该函数不会抛出 NullPointerException 。
下面的程序说明了 java.util.Dictionary.remove() 方法的使用。
程序1 :
// Java Program to illustrate
// java.util.Dictionary.remove() method
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Create a new hashtable
Dictionary<Integer, String>
d = new Hashtable<Integer, String>();
// Insert elements in the hashtable
d.put(1, "Geeks");
d.put(2, "for");
d.put(3, "Geeks");
// Print the Dictionary
System.out.println("\nDictionary: " + d);
// Display the removed value
System.out.println(d.remove(3)
+ " has been removed");
// Print the Dictionary
System.out.println("\nDictionary: " + d);
}
}
输出。
Dictionary: {3=Geeks, 2=for, 1=Geeks}
Geeks has been removed
Dictionary: {2=for, 1=Geeks}
程序2 。
// Java Program to illustrate
// java.util.Dictionary.remove() method
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Create a new hashtable
Dictionary<String, String> d = new Hashtable<String, String>();
// Insert elements in the hashtable
d.put("a", "GFG");
d.put("b", "gfg");
// Print the Dictionary
System.out.println("\nDictionary: " + d);
// Display the removed value
System.out.println(d.remove("a")
+ " has been removed");
System.out.println(d.remove("b")
+ " has been removed");
// Print the Dictionary
System.out.println("\nDictionary: " + d);
// returns true
if (d.isEmpty()) {
System.out.println("Dictionary "
+ "is empty");
}
else
System.out.println("Dictionary "
+ "is not empty");
}
}
输出。
Dictionary: {b=gfg, a=GFG}
GFG has been removed
gfg has been removed
Dictionary: {}
Dictionary is empty
**参考资料: ** https://docs.oracle.com/javase/7/docs/api/java/util/Dictionary.html#remove()