Java重写equals方法判断对象是否相等案例

public class HelloWorl
{
    
    	
	public static void main(String[] args)
	{
    
    	
		Data a = new Data(2017,7,28);		
		Data c = new Data(2017,7,28);
		if(a.equals(c)) System.out.println("true");
		else System.out.println("false");
		
		Data d = a;
		if(a.equals(d)) System.out.println("true");
	}
}
 
 
class Data
{
    
    
	int year;
	int month;
	int day;
	Data(int year,int month,int day)
	{
    
    
		this.year = year;
		this.month = month;
		this.day = day;
	}
	public boolean equals(Object x)
	{
    
    
		if(this == x) return true;
		if(x == null) return false;	//能调用这个方法,this肯定不为null,所以不判断this
		if(this.getClass() != x.getClass()) return false; //如果不死同一个类,则必然false
		Data that = (Data)x; //将Object类型的x转换为Data型。因为上一行已经判断了x是否为Data型,所以可以直接转换
		
		if(this.year != that.year) return false;
		if(this.month != that.month) return false;
		if(this.day != that.day) return false;
		
		return true;		
	}	

猜你喜欢

转载自blog.csdn.net/WziH_CSDN/article/details/108779515