equals方法重写
在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); } }
相比较上面两种,第三种更为严谨。