大家好,小弟菜鸟有个关于HashTable的问题。现在想通过一个国家的英文名称和ID,找到对应的中文名称。
step1:自定义一个HashTable的关键字类
package com..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..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;
}

解决方案 »

  1.   

    如果要忽略大小写 则 hashCode方法要这样修改下:
    public int hashCode() { return countryName.toLowerCase().hashCode() + countryID;
    }
      

  2.   

    恩,你的equals里面是忽略大小写了,但你的hashcode里没有,你这样写也不符合equals必hashcode相同的结论,改成2楼那样就行了