java问题 看了张孝祥JAVA的课题
//主要有两个类 以下是驱动类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.toString() + "="); //第一个问题 为什么key.toString中的toString加不加一样
System.out.println(numbers.get(key));
}
System.out.println(numbers.get(new MyKey("zhangsan",18)));
}
}
//-------------------以下是驱动类调用的类 MyKey---
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 String toString(){
return name + "," + age;
}
public int hashCode(){
return name.hashCode() + age; //第二个问题 为什么name可以直接调用hashCode
}
public MyKey(String s ,int i ){
this.name = s;
this.age = i;
}
}
[ 本帖最后由 kkllchun 于 2010-2-9 17:19 编辑 ]