Hashtable类
不仅可以像Vector一样动态存储一系列的对象,而且对存储的每一个对象
(称为值)都要安排另一个对象(称为关键字)与之相关联。
Hashtable numbers = Hashtable();
numbers.put("one",new Integer(1));
numbers.put("two",new Integer(2));
Hashtable中不能有重复的关键字,put中若有相同的关键字将会修改原有的值。
Integer n = (Integer)numbers.get("two");
if( n != null)
System.out.println("two = " + n);
用作关键字的类必须覆盖Object.hashCode方法和Object.equals方法
编程举例:使用自定义类作为Hashtable的关键字
public class MyKey
{
private String name = null;
private int age = 0;
Public MyKey(String name,int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return name + "," +age;
}
public boolean equals(Object obj)
{
if(obj instanceof MyKey)
{
MyKey objTemp = (MyKey)obj;
if(name.equals(objTemp.name) && age == objTemp.age)
{
return true;
}
else
{
reture false;
}
}
else
{
return false;
}
}
public int hashCode()
{
return name.hashCode() + age;
}
}
StringBuffer类不能作为Hashtable关键字
public static void main(String[] args)
{
Hashtable numbers = new Hashtable();
number.put(new MyKey("zhangsan",18),new Integer(1));
number.put(new MyKey("lisi",15),new Integer(2));
number.put(new MyKey("wangwu",20),new Integer(3));
Enumeration e = number.keys();
while(e.hasMoreElements())
{
MyKey key = (MyKey)e.nextElement();
System.out.print(key.toString() + "=");
System.out.println(numbers.get(key));
}
}