本帖最后由 monghuan 于 2011-12-16 16:12 编辑
- import java.util.*;
- public class TestHashtable {
- public static void main(String[] args) {
- Hashtable s = new Hashtable();
- s.put(new MyKey("zhangsan",20),new Integer(1));
- s.put(new MyKey("lisi",23),new Integer(2));
- Enumeration e = s.keys();
- while(e.hasMoreElements())
- {
- MyKey mk = (MyKey)e.nextElement();
- System.out.println(mk.name+","+mk.age+":"+s.get(mk));
- }
-
- }
- }
- class MyKey {
- public String name = "unknown";
- public int age = 0;
- /**
- * Method Mykey
- *
- *
- */
- public MyKey(String name,int age) {
- this.name = name;
- this.age = age;
- }
- public boolean equals(Object obj) {
- if(obj instanceof MyKey)
- {
- MyKey objt = (MyKey)obj;
- if(name.equals(objt.name) && age==objt.age) //-------这边应该是"objt.name",而不是"objt",虽然我知道你是不小心写的,但我还是想打你一顿
- return true;
- else
- return false;
- }
- else
- return false;
- }
- public int hashCode() {
- return name.hashCode()+age;
- }
- }
-
复制代码 运行结果: |