黑马程序员技术交流社区
标题:
重写equals方法的妙用
[打印本页]
作者:
森仔
时间:
2012-11-21 19:12
标题:
重写equals方法的妙用
public class Student {
private String name;
private int age;
private boolean gender;
public Student(String name, int age, boolean gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
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 boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
//return super.equals(obj);
if(obj instanceof Student)
{
final Student other = (Student) obj;
if(this.name.equals(other.name)&&this.age==other.age)
{
return true;
}
}
return false;
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
Student s1=new Student("张三",20,true);
Student s2=new Student("张三",20,true);
System.out.println(s1==s2);
System.out.println(s1.equals(s2));//重写equals方法后相等返回true,如果不重写,则直接调用父类(Object)的equals方法,比较的还是地址是否相等
}
}
作者:
许庭洲
时间:
2012-11-21 20:34
值得学习ing!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2