为什么不能强制转换 成Hashtable
import java.util.*;public class TestHashtable {
public static void main(String [] args){
Hashtable numbers= new Hashtable();
numbers.put(new MyKey("zhangsan",18),new Integer(1));
numbers.put(new MyKey("lisi",19),new Integer(2));
numbers.put(new MyKey("wangwu",20),new Integer(3));
Enumeration e = numbers.keys();
while(e.hasMoreElements()){
MyKey key = (MyKey)e.nextElement();
System.out.print(key + "=");
System.out.println(numbers.get(key));
}
MyKey key1 = new MyKey("zhangsan",18);
System.out.println(numbers.get( key1 ));
MyKey key2 = (Hashtable)new MyKey("lisi",110);//为什么不能用这种转换呢
System.out.println(numbers.get( key1 )); //我理解成这样就不用在MyKey中写Hashcode方法了 因为 已经强制转换成Hashtable已经有这个方法
}
// -----------------------------------------------------------------
public class MyKey {
private String name = null;
private int age = 0;
public boolean equals(Object obj){
if(obj instanceof MyKey){
MyKey objTemp = (MyKey)obj;
if(name.equals(objTemp.name) && age == objTemp.age){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
public int hashCode(){
return name.hashCode() + age;
}
public MyKey(String s ,int i ){
this.name = s;
this.age = i;
}
public String toString(){
return name + "XP" + age;
}
}