当前位置: 代码迷 >> J2SE >> equals跟hasCode疑惑
  详细解决方案

equals跟hasCode疑惑

热度:184   发布时间:2016-04-24 17:19:41.0
equals和hasCode疑惑
代码如下:
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呢?


------解决方案--------------------
public int hashCode();
不是hasCode()
  相关解决方案