一个关于HashTable的问题

MARKtft 2009-05-01 11:15:37
大家好,小弟菜鸟有个关于HashTable的问题。现在想通过一个国家的英文名称和ID,找到对应的中文名称。
step1:自定义一个HashTable的关键字类
package com.mark.Hashtable;
public class MyCountry {
private String countryName = null;
private int countryID = 0;
public boolean equals(Object obj) {
if(obj instanceof MyCountry)
{
MyCountry tempObj = (MyCountry)obj;
//忽略字符串大小写
if(countryName.equalsIgnoreCase(tempObj.countryName) && countryID == tempObj.countryID)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public int hashCode(){

return countryName.hashCode() + countryID;
}

public MyCountry(String countryName,int countryID) {

this.countryName = countryName;
this.countryID = countryID;
}
}
Step2:运行类
package com.mark.Hashtable;
import java.util.*;
public class HashTableTest001 {

public static void main(String[] args) {

Hashtable countryObj = new Hashtable();
countryObj.put(new MyCountry(new String("China"),1000),new String("中国"));
countryObj.put(new MyCountry(new String("America"),1001),new String("美国"));

System.out.print(countryObj.get(new MyCountry("china",1000)).toString()); //抛出NullPointException,在MyCountry的equlas()方法中,忽略大小写的caseIngore()没有起作用
System.out.print(countryObj.get(new MyCountry("China",1000)).toString()); //正常返回结果:中国

}
}

问题:
在HashTableTest001 类的System.out.print(countryObj.get(new MyCountry("china",1000)).toString())该行中,输入小写的"china"。
并没有返回希望的结果 "中国" ,实际上返回了一个null。
请问大家,我在MyCountry类做的忽略大小写的判断为什么不起作用?
if(countryName.equalsIgnoreCase(tempObj.countryName) && countryID == tempObj.countryID)
{
return true;
}
else
{
return false;
}
...全文
46 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
老牛1 2009-05-02
  • 打赏
  • 举报
回复
如果要忽略大小写 则 hashCode方法要这样修改下:
	public int hashCode() {

return countryName.toLowerCase().hashCode() + countryID;
}
gesanri 2009-05-02
  • 打赏
  • 举报
回复
恩,你的equals里面是忽略大小写了,但你的hashcode里没有,你这样写也不符合equals必hashcode相同的结论,改成2楼那样就行了
montao 2009-05-01
  • 打赏
  • 举报
回复
mark 猪

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧