banditdaren
土豆烧牛肉1985
2009-04-06 10:11

Hashtable的get(key)问题,望解答

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

我先定义了一个MyKey作为hashtable的关键字,而且在MyKey中重写了hashCode()和equals()函数。
但是在hashtable中还是检索不到key值对应的值,
1)
package lesson6;

public class MyKey {
private String name = null;
private int age = 0;

MyKey(String name, int age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public boolean equals(Object obj) {

    if (obj instanceof MyKey) {
        MyKey objTemp = (MyKey) obj;
        if (this.name.equals(objTemp.name) && this.age == objTemp.age) {
            return true;
        } else
            return false;

    } else {
        return false;
    }

}

public int haseCode() {

    return name.hashCode() + age;

}

public String toString() {
    return name + "," + age;
}

}
2)
package lesson6;

import java.util.*;

public class HashtableTest {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Hashtable numbers = new Hashtable();
    numbers.put(new MyKey("zhangsan", 18), new Integer(1));
    numbers.put(new MyKey("lisi", 15), new Integer(2));
    numbers.put(new MyKey("zhangsan1", 19), new Integer(3));
    numbers.put(new MyKey("zhangsan2", 20), new Integer(4));
    Enumeration e = numbers.keys();
    while (e.hasMoreElements()) {
        MyKey key = (MyKey) e.nextElement();
        System.out.print(key + "=");
        System.out.println(numbers.get(key));
        System.out.println(key.getName().hashCode());
        System.out.println(key.hashCode());
    }

    MyKey ko = new MyKey("lisi", 15);
    // System.out.println("lisi".hashCode()+15);
    // System.out.println(ko.haseCode());
    System.out.println(numbers.get(ko));
}

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换