f*********i 发帖数: 197 | 1 我自己写了一个类
static class Mix{
public int a; double b; String c;
Mix(int a,double d,String c){
this.a=a;this.b=d;this.c=c;
}
public int hashCode(){
return 1;
}
}
在main函数中,我创建了两个一样的实例,但是hashtable认为他们是不一致的,我已
经重载了这个类的hashCode这个函数了啊。应该如何处理呢?
public static void main(String[] args)
Mix m1 = new Mix(1,0.53,"yes");
Mix m2 = new Mix(1,0.52,"yes");
System.out.println(m1.hashCode());
System.out.println(m2.hashCode());
Hashtablehash = new Hashtable();
hash.put(m1, m1.hashCode());
if(hash.get(m2)!=null)
System.out.println("found");
else
System.out.println("not found");
System.out.println(hash.get(m1));
}
输出
1
1
not found
1
如何才能让hashtable认为它们一致呢,是我写错了覆盖函数吗? | g*****g 发帖数: 34805 | 2 You also need to implement equals, always do these two in pair.
【在 f*********i 的大作中提到】 : 我自己写了一个类 : static class Mix{ : public int a; double b; String c; : Mix(int a,double d,String c){ : this.a=a;this.b=d;this.c=c; : } : public int hashCode(){ : return 1; : } : }
| f*********i 发帖数: 197 | 3 static class Mix{
public int a; double b; String c;
Mix(int a,double d,String c){
this.a=a;this.b=d;this.c=c;
}
public int hashCode(){
return 1;
}
public boolean equals(Mix mix){
if(this.hashCode()==mix.hashCode())
return true;
else
return false;
}
}
我已经override equals了,还是没有效果啊 | g*****g 发帖数: 34805 | 4 This is not an override.
Try
public boolean equals(Object o)
【在 f*********i 的大作中提到】 : static class Mix{ : public int a; double b; String c; : Mix(int a,double d,String c){ : this.a=a;this.b=d;this.c=c; : } : public int hashCode(){ : return 1; : } : public boolean equals(Mix mix){ : if(this.hashCode()==mix.hashCode())
| r*****l 发帖数: 2859 | 5 Learn to use @Override
【在 f*********i 的大作中提到】 : static class Mix{ : public int a; double b; String c; : Mix(int a,double d,String c){ : this.a=a;this.b=d;this.c=c; : } : public int hashCode(){ : return 1; : } : public boolean equals(Mix mix){ : if(this.hashCode()==mix.hashCode())
|
|