• Java 数据结构教程

从字典中移除元素



您可以使用字典类的remove()方法移除字典中的元素。此方法接受键或键值对并删除相应的元素。

dic.remove("Ram");
or
dic.remove("Ram", 94.6);

示例

import java.util.Hashtable;
import java.util.Dictionary;

public class RemovingElements {
   public static void main(String args[]) {
      Dictionary dic = new Hashtable();
      dic.put("Ram", 94.6);
      dic.put("Rahim", 92);
      dic.put("Robert", 85);
      dic.put("Roja", 93);
      dic.put("Raja", 75);

      System.out.println("Contents of the hash table :"+dic); 
      dic.remove("Ram");
      System.out.println("Contents of the hash table after deleting specified elements :"+dic); 
   }
}

输出

Contents of the hash table :{Rahim = 92, Roja = 93, Raja = 75, Ram = 94.6, Robert = 85}
Contents of the hash table after deleting specified elements :{Rahim = 92, Roja = 93, Raja = 75, Robert = 85}
广告