equals方法的重写代码实例

来源:互联网 发布:数控下料编程软件 编辑:程序博客网 时间:2024/05/31 13:14
/**
*
*/
/**
*
* @2014-8-20
* @TODO 这篇文章主要是要记录一下equals的重写,下面上代码,代码里有足够的注释
*/
public class Citizen {
    String id;// 身份证号
    String name;// 名字
    intage; // 年龄
    String sex;// 性别
    // 用构造方法对成员变量进行初始化
    publicCitizen(String theId, String theName, inttheAge, String theSex) {
        this.id = theId;
        this.name = theName;
        this.age = theAge;
        this.sex = theSex;
    }
    // 重写equals()方法
    publicboolean equals(Object obj) {
        // 首先需要判断obj是否为null, 如果为null,返回false
        if (obj == null) {
            return false;
        }
        // 判断测试的是否为同一个对象,
        // 如果是同一个对象,无庸置疑,它应该返回true
        if (this== obj) {
            return true;
        }
        // 判断它们的类型是否相等,
        // 如果不相等,则肯定返回false
        if (this.getClass() != obj.getClass()) {
            return false;
        }
        // 将参数中传入的对象造型为Citizen类型
        Citizen c = (Citizen) obj;
        // 比较两个对象的所有属性是否一样,就可以得出这两个对象是否相等
        if ((this.id) == (c.id) && (this.name).equals(c.name)
               && (this.age) == (c.age) && (this.sex).equals(c.sex)) {
            return true;
        }else {
            return false;
        }
    }
}
 
 
public class TestCitizen
{
    publicstatic void main(String[] args)
    {
        Citizen c1 = newCitizen("id00001","zhangsan",20,"男");
        Citizen c2 = newCitizen("id00001","zhangsan",20,"男");
        System.out.println(c1.equals(c2));
    }
}
 
0 0
原创粉丝点击