equals方法的重写代码实例

这篇文章主要是要记录一下equals的重写,下面上代码,代码里有足够的注释

/**
 * 
 */

/**
 * @author laishengfeng
 * @2014-8-20
 * @TODO equals方法的重写
 */
public class Citizen {

	String id; // 身份证号
	String name; // 名字
	int age; // 年龄
	String sex; // 性别

	// 用构造方法对成员变量进行初始化
	public Citizen(String theId, String theName, int theAge, String theSex) {
		this.id = theId;
		this.name = theName;
		this.age = theAge;
		this.sex = theSex;
	}

	// 重写equals()方法
	public boolean 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;
		}

	}
}

上面是重写的具体过程

然后 用一个测试类 来进行验证

/**
 * 
 */

/**
 * @author laishengfeng
 * @2014-8-20
 * @TODO 测试Citizen类
 */
public class TestCitizen
{
	public static void main(String[] args)
	{
		Citizen c1 = new Citizen("id00001","zhangsan",20,"男");
		Citizen c2 = new Citizen("id00001","zhangsan",20,"男");
		System.out.println(c1.equals(c2));
	}
}

  此文到此END..

转载于:https://my.oschina.net/lsf930709/blog/304660

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值