有这样一段程序:
class Groundhog {
int ghNumber;
Groundhog(int n){
ghNumber = n;
}
public String toString(){
return "Groundhog "+ghNumber;
} public int hashcode(){return ghNumber;} public boolean equals(Object o){
return (o instanceof Groundhog)
&& (ghNumber == ((Groundhog)o).ghNumber);
}
}class Prediction{
boolean shadow = Math.random() > 0.5;
public String toString(){
if(shadow)
return"Six more weeks of Winter!";
else
return "Early Spring!";
}
}public class TestHash {
public static void main(String[] args){
HashMap hm = new HashMap();
for (int i = 0; i < 10; i++)
hm.put(new Groundhog(i),new Prediction());
Groundhog gh = new Groundhog(9);
if(hm.containsKey(gh))
System.out.println((Prediction)hm.get(gh));
else
System.out.println("Key not Found:"+gh);
}
}
结果是:
Key not Found:Groundhog 9我已经覆写了hashcode()和equals()方法,为什么还是出现这个结果
class Groundhog {
int ghNumber;
Groundhog(int n){
ghNumber = n;
}
public String toString(){
return "Groundhog "+ghNumber;
} public int hashcode(){return ghNumber;} public boolean equals(Object o){
return (o instanceof Groundhog)
&& (ghNumber == ((Groundhog)o).ghNumber);
}
}class Prediction{
boolean shadow = Math.random() > 0.5;
public String toString(){
if(shadow)
return"Six more weeks of Winter!";
else
return "Early Spring!";
}
}public class TestHash {
public static void main(String[] args){
HashMap hm = new HashMap();
for (int i = 0; i < 10; i++)
hm.put(new Groundhog(i),new Prediction());
Groundhog gh = new Groundhog(9);
if(hm.containsKey(gh))
System.out.println((Prediction)hm.get(gh));
else
System.out.println("Key not Found:"+gh);
}
}
结果是:
Key not Found:Groundhog 9我已经覆写了hashcode()和equals()方法,为什么还是出现这个结果
public int hashCode(){return ghNumber;}
注意大小写