`

【转】JAVA中重写equals()方法为什么要重写hashcode()方法说明【三】

    博客分类:
  • Java
 
阅读更多

 

重写equals()方法 
下面给出编写一个完美的equals方法的建议:

1) 显式参数命名为otherObject,稍后需要将它转换成另一个叫做 other的变量。

2) 检测this与otherObject是否引用同一个对象:

        if (this == otherObject) return true;

        这条语句只是一个优化。实际上,这是一种经常采用的形

        式。因为计算这个等式要比一个一个地比较类中的域所付

        出的代价小得多。

3) 检测otherObject是否为null,如果为null,返回false。这项 检测是很必要的。

                if (otherObject == null) return false;

      比较this与otherObject是否属于同一个类。如果equals的语义在每个子类中有所改变,就使用getClass检测:

              if (getClass() != otherObject.getClass()) return false;

      如果所有的子类都拥有统一的语义,就使用instanceof检测:

              if (! (otherObject instanceof ClassName)) retrun false;

4)将otherObject转换为相应的类类型变量:

        ClassName other = (ClassName)otherObject;

5) 现在开始对所有需要比较的域进行比较了。使用 == 比较基本类型域,使用equals比较对象域。如果所有的域都匹 配,就返回ture;否则返回false。

===============================华丽的分割线===============================

转载:http://xyiyy.iteye.com/blog/359219

下面是一个根据业务键实现equals()与hashCode()的例子。实际中需要根据实际的需求,决定如何利用相关的业务键来组合以重写这两个方法。

public class Cat 
{
	private String name;
	private String birthday;

	public Cat()
	{
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getName()
	{
		return name;
	}

	public void setBirthday(String birthday)
	{
		this.birthday = birthday;
	}

	public String getBirthday()
	{
		return birthday;
	}

       //重写equals方法
	public boolean equals(Object other)
	{
		if(this == other)
		{
			//如果引用地址相同,即引用的是同一个对象,就返回true
			return true;
		}

            //如果other不是Cat类的实例,返回false
		if(!(other instanceOf Cat))
		{
			return false;
		}

		final Cat cat = (Cat)other;
            //name值不同,返回false
		if(!getName().equals(cat.getName())
			return false;
            //birthday值不同,返回false
		if(!getBirthday().equals(cat.getBirthday()))
			return false;

		return true;
	}

       //重写hashCode()方法
	public int hashCode()
	{
		int result = getName().hashCode();
		result = 29 * result + getBirthday().hashCode();
		return result;
	}
}

 

重写父类方法的原则:可以重写方法的实现内容,成员的存取权限(只能扩大,不能缩小),或是成员的返回值类型(但此时子类的返回值类型必须是父类返回值类型的子类型)。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics