处理hashCode()和equals()
import java.util.Objects;
public class Man {
private String noseSize;
private String eyesColor;
private String haircut;
private boolean scars;
private int dnaCode;
public Man(String noseSize, String eyesColor, String haircut, boolean scars, int dnaCode) {
this.noseSize = noseSize;
this.eyesColor = eyesColor;
this.haircut = haircut;
this.scars = scars;
this.dnaCode = dnaCode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (getClass() != o.getClass()) return false;
Man man = (Man) o;
return dnaCode == man.dnaCode;
}
public String getNoseSize() {
return noseSize;
}
public void setNoseSize(String noseSize) {
this.noseSize = noseSize;
}
public String getEyesColor() {
return eyesColor;
}
public void setEyesColor(String eyesColor) {
this.eyesColor = eyesColor;
}
public String getHaircut() {
return haircut;
}
public void setHaircut(String haircut) {
this.haircut = haircut;
}
public boolean isScars() {
return scars;
}
public void setScars(boolean scars) {
this.scars = scars;
}
public int getDnaCode() {
return dnaCode;
}
public void setDnaCode(int dnaCode) {
this.dnaCode = dnaCode;
}
}
equals我似乎知道这是如何工作的,在构造函数中,在我编写的 setter 中,但通常是if (this == o) return true;这样。
this指向和往常一样,指向类的一个实例Man这是链接比较。
而表达式的含义是
if (this == o) return true;完成检查并返回true是否equals将同一对象传递给方法。