提示:判断是否相等的时候有时还会调用hash()方法,所以,有时我们还需要同时重写hashcode();
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object arg0) {
//1.如果引用相同,直接返回true
if(arg0==this)
return true;
//2.如果参数为空,直接false
if(arg0==null)
return false;
//1.判断是否Student的实例,getClass()比instanceof更合适
if(!(arg0.getClass()!=this.hetClass())
return false;
//2.类型强转
Student stu=(Student)arg0;
if(stu.id==this.id&&stu.name!=null&&this.name!=null&&stu.name.equals(this.name)&&stu.age==this.age)
return true;
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return 1;
}
public static void main(String[] args) {
Student s1=new Student(1,"lili",12);
Student s2=new Student(1,"lili",12);
System.out.println(s1.equals(s2)+" "+(s1.hashCode()==s2.hashCode()));
}
}
从程序输出可以看出,instanceof进行类型检查规则是:你属于该类吗?或者你属于该类的派生类吗?而通过getClass获得类型信息采用==来进行检查是否相等的操作是严格的判断。不会存在继承方面的考虑; Java语言规范要求equals自反性,所以getClass()比instanceof更合适。