Java中的字典remove()方法
Dictionary 类的remove()方法接受一个键作为参数,并删除映射到该键的相应值。
句法:
public abstract V remove(Object key)
参数:该函数接受一个参数键,该键表示要从字典中删除的键及其映射。
返回值:该函数返回映射到键的值,如果键没有映射,则返回NULL 。
异常:如果作为参数传递的键为NULL ,则该函数不会引发NullPointerException 。
下面的程序说明了Java.util.Dictionary.remove()方法的使用:
方案一:
// 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
d = new Hashtable();
// 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}
方案二:
// 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 d = new Hashtable();
// 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: Java/util/Dictionary.html#remove()