Redian新闻
>
问个hashtable实现问题
avatar
问个hashtable实现问题# Java - 爪哇娇娃
f*i
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认为它们一致呢,是我写错了覆盖函数吗?
avatar
g*g
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;
: }
: }

avatar
f*i
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了,还是没有效果啊
avatar
g*g
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())

avatar
r*l
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())

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。