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

我先定义了一个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个回答

[code="java"]

public int haseCode() {

return name.hashCode() + age;

} [/code]

方法名写错了,笔误
[code="java"]

public int hashCode() {

return name.hashCode() + age;

} [/code]

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问