equals方法重寫
阿新 • • 發佈:2017-05-23
else 另有 舉例 spa all == ring pub 自定義類
在java中常見的equals方法的重寫:
舉例:一個自定義類ball如下
public class Ball { private String name; private int weight; public Ball(String name,int weight){ this.name = name; this.weight = weight; } }
我們可以這樣重寫equals方法:
public boolean equals(Object obj){ if(obj == null){return false; }else{ if(obj instanceof Ball){ Ball ball = (Ball)obj; if(this.name == ball.name&&this.weight==ball.weight){ return true; } } } return false; }
另有更簡介方法如下:
public boolean equals(Object obj){
if(obj instanceof Ball){
Ball ball = (Ball)obj;
return this.name==ball.name&&this.weight==ball.weight)
else{
return super.equals(obj);
}
}
更嚴謹的寫法:
public boolean equals(Object obj){if(obj instanceof Ball){ Ball ball = (Ball)obj; return this.name.equals(obj.name)&& this.weight.equals(ball.weight); else{ return super.equals(obj); } }
相比較上面兩種,第三種更為嚴謹。
equals方法重寫