Hashtable类的用法

 
实现了Map接口,是同步的哈希表,不允许类型为null的键名和键值。哈希表主要用于存储一些映射关系。这个类比较特殊,与Collection中的其它的类不太一样,首先它是同步的,另外它是继承自java.util.Dictionary类。
一个典型的应用就是在连接数据库的时候,需要提供各种参数,包括主机、端口、数据库ID、用户名、口令等,可以把这些信息先存储在哈希表中,然后最为参数使用。
下面通过例子来介绍Hashtable的使用。
package com.li.collection;
 
import java.util.Hashtable;
 
public class HashtableTest {
 public static void main(String[] args) {
    HashtableTest hashtabletest = new HashtableTest();
    hashtabletest.test();
 }
 public void test()
 {
    Hashtable colors = new Hashtable();
    //创建Hashtable对象
    colors.put("red","红色");
    colors.put("black","黑色");
    colors.put("gray","灰色");
    colors.put("blue","蓝色");
    colors.put("green","绿色");
    colors.put("yellow","黄色");
    colors.put("white","白色");
    //向Hashtable中添加元素
   
    System.out.println("元素:"+colors.toString());
   
    boolean b = colors.containsKey("red");
    //判断是否包含键red
    System.out.println("是否包含键red:"+b);
   
    b = colors.containsValue("red");
    //判断是否包含值red
    System.out.println("是否包含值red:"+b);
   
    String temp = (String)colors.get("black");
    //获取键为black的值
    System.out.println("键black对应的值为:"+temp);
   
    colors.remove("gray");
    //删除键为gray的元素
    System.out.println("删除gray之后:"+colors.toString());
   
    System.out.println("元素个数为:"+colors.size()); //获取元素个数
 
    colors.clear(); //清空对象
    System.out.println("清空之后:"+colors.toString());
 }
}
运行结果为:
元素:{blue=蓝色, gray=灰色, white=白色, green=绿色, red=红色, yellow=黄色, black=黑色}
是否包含键red:true
是否包含值red:false
键black对应的值为:黑色
删除gray之后:{blue=蓝色, white=白色, green=绿色, red=红色, yellow=黄色, black=黑色}
元素个数为:6
清空之后: {} 

你可能感兴趣的:(106,常用类库)