编写那个汉诺塔和消息分发的时候遇到的,只重写euqals是为了使得能够比较两个同一个类的对象的内容是否相同,而假如有一个hashmap里面存的一个a和b对象,但是你要想比较他们的 内容是否相同,那你就得重写HashCode()和equals()方法
下面是代码
package org.wxyteam.rookie.message;
public class SimpleMessageDescriptor implements IMessageDescriptor {
private final byte typeCode;
private final byte functionCode;
public SimpleMessageDescriptor(int typeCode, int functionCode) {
this((byte) typeCode, (byte) functionCode);
}
public SimpleMessageDescriptor(byte typeCode, byte functionCode) {
this.typeCode = typeCode;
this.functionCode = functionCode;
}
@Override
public byte getMessageTypeCode() {
return this.typeCode;
}
@Override
public byte getMessageFunctionCode() {
return this.functionCode;
}
//十分关键(是map那个实现要用的):因为hashmap中查找一个key为对象的时候,比如get(a)其中a是一个对象,这时候就算是hash表中比如有一个对象b的各种属性和a都相同,
// 但是却无法查找成功。这是因为hashmap是根据对象的hash值进行查找的,不同对象(尽管他们属性值相同,但是地址不一样)查出来的hash值是不一样的,
// 这样就导致明明a和b一样(这个一样只是指属性值一样),却查不出来value,这时候要想实现这种查找,就得重写你要比较的类的hash方法和equal方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((typeCode == 0) ? 1 : typeCode);
result = prime * result + ((functionCode == 0) ? 1 : functionCode);
return result;
}
@Override
public boolean equals(Object obj) {
if(obj==null){
return false;
}
if(this==obj){
return true;
}
if(obj instanceof SimpleMessageDescriptor){
SimpleMessageDescriptor dog=(SimpleMessageDescriptor)obj;
if(dog.typeCode==this.typeCode&&dog.functionCode==(this.functionCode)){
return true;
}else{
return false;
}
}
return false;
}
}