当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Dictionary remove()用法及代码示例


字典类的remove()方法接受键作为参数,并删除映射到该键的对应值。

用法:

public abstract V remove(Object key)

参数:该函数接受参数键,该参数键表示将与字典及其映射一起从字典中删除的键。


返回值:该函数返回已映射到键的值,如果键没有映射,则返回NULL。

异常:如果作为参数传递的键为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()



相关用法


注:本文由纯净天空筛选整理自RICHIK BHATTACHARJEE大神的英文原创作品 Dictionary remove() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。