java中的每个对象都有一个唯一的hashcode与它对应,就跟一个地址一样。两个相同的字符串hashcode值也是一样。
在程序中,我们碰到了需要判断名字变种是否相等的问题。比如abc型的有许多的形式,abc,bc a等。我们最后采用的判断它们相等的方法是:(abc+bca).hashcode.
map<author>判断其中的元素相等,需要首先调用hashcode() 方法,然后调用equals方法。
改造的author中的hashcode方法:
public int hashCode() {
if(nameValue!=0)
{
return nameValue;
}
final int prime = 31;
int result = 1;
//String str= PinyinUtils.getFirstCharOfName(name);
if(this.firstCharOfName.length()==3)
{
if(name==null)
result=prime*result;
else
{
result = prime * result +this.firstCharOfName.hashCode()
+this.shortName1.hashCode()
+this.shortName2.hashCode();
}
}
else if(this.firstCharOfName.length()==2)
{
if(name==null)
result=prime*result;
else
{
result = prime * result +this.firstCharOfName.hashCode()
+this.shortName1.hashCode();
}
}
else if(this.firstCharOfName.length()==4)
{
if(name==null)
result=prime*result;
else
{
result = prime * result +this.firstCharOfName.hashCode()
+this.shortName1.hashCode();
}
}
result=result*961;
nameValue=result;
return result;
}