您的位置:程序门 -> java -> j2se / 基础类



equals和hascode疑惑


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


equals和hascode疑惑[已结贴,结贴人:xandon01]
发表于:2007-02-27 10:39:21 楼主
代码如下:
package   test;

import   java.util.*;

final   class   student   {
string   name;

int   age;

public   student(string   name,   int   age)   {
this.name   =   name;
this.age   =   age;
}

public   boolean   equals(object   o)   {
if   (o   ==   this)
return   true;
if   (!(o   instanceof   student))
return   false;
student   s   =   (student)   o;
if   (s.name   ==   name   &&   s.age   ==   age)
return   true;
else
return   false;
}

public   int   hascode()   {
return   name.hashcode()   +   age;
}

}

public   class   test1   {
public   static   void   main(string   args[])   {
map   map   =   new   hashmap();
student   s1   =   new   student( "lwb ",   26);
student   s2   =   new   student( "lwb ",   26);
map.put(s1,   "s1 ");
system.out.println(map.get(s2));
}

}

已经重写了equals和hascode,为什么运行结果为null呢?
发表于:2007-02-27 10:47:491楼 得分:20
public   int   hashcode();
不是hascode()
发表于:2007-02-27 11:16:192楼 得分:0
不是hascode
是hashcode
更正后测试输出
s1


快速检索

最新资讯
热门点击