equals方法

两个需要重写的方法:toString方法、equals方法

  • ==判断两个引用变量,要求两个引用变量指向同一个对象时,才会返回true。

  • 【默认的equals方法】:Object提供的equals方法,判断两个对象相等的标准与==是完全一样的。

  • 重写equals方法:根据业务规则来提供两个对象相等的标准。实际项目中,用来作为equals比较的关键成员变量,通常并不需要使用全部的成员变量----只需要它们关键的成员变量即可。

  • 对于字符串:String已经重写了equals方法,只要两个字符串的字符内容相等,就会返回true。

class Goat
{
	private String color;
	private double weight;
	public Goat()
	{
	}
	public Goat(String color,double weight)
	{
		this.color = color;
		this.weight = weight;
	}
	public void setColor(String color)
	{
		this.color = color;
	}
	public void setWeight(double weight)
	{
		this.weight = weight;
	}
	public String getColor()
	{
		return this.color;
	}
	public double getWeight()
	{
		return this.weight;
	}
	@override
	public boolean equals(Object obj)
	{
		//this和obj指向同一个对象
		if(this == obj)
		{
			return ture;
		}
		//obj不为null,且obj必须为Goat
		if(obj != null && obj.getClass() = = Goat.class)
		{
			//对obj强转为Goat
			Goat target = (Goat)obj;
			//比较关键属性
			return this.color.equals(obj.color) && this.weight == obj.weight;
		}
	}
}
public class EqualsTest
{
	public static void main(String[] args)
	{
		Goat goat1 = new Goat("黑色",78.2);
		Goat goat2 = new Goat("黑色",78.2);
		//goat1和goat2分别指向两个不同的对象,因此==判断返回false
		System.out.println(goat1 == goat2); 
		System.out.println(goat1.equals(goat2)); 
		
	}
}
posted @ 2020-02-11 12:32  又又又8  阅读(110)  评论(0)    收藏  举报