码迷,mamicode.com
首页 > 其他好文 > 详细

equals方法的重写代码实例

时间:2014-08-20 14:33:52      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:java   ar   2014   代码   amp   new   sp   c   

这篇文章主要是要记录一下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..

equals方法的重写代码实例,布布扣,bubuko.com

equals方法的重写代码实例

标签:java   ar   2014   代码   amp   new   sp   c   

原文地址:http://my.oschina.net/lsf930709/blog/304660

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!