java中判断类对象是否相等的方法

   ==操作符判断的是地址是否相等,equals()判断的是内容是否相等。判断类是否相等要重写equals()方法,

一种方法是用hashcode()和equals()方法,另一种方法用instanceof()

instanceof 是保留关键字,作用是判断左边的对象是否是右边类的实例。

instanceof方法:

public class Birds {
	private int weight;
	private String name;
	public Birds(){
		this.weight = 140;
		this.name = "huanghe";
	}
	
	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public String getName() {
		return name;
	}

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

	
	public boolean equals(Object obj) {
		if (obj == this) return true;
		if (obj instanceof Birds) {
			if (!((Birds) obj).name.equals(name)) return false;
			if (!(((Birds)obj).weight == weight)) return false;
		}
		return true;
	}
//	public boolean equals(Object anObject) {
//		// TODO Auto-generated method stub
//		//如果是引用类型  判断内存地址是否相同     
//		//如果是 基本数据类型  判断值是否相等
//		if (this == anObject) {
//	        return true;
//	    }
//	    if (anObject instanceof String) {
//	    	//判断类里的属性值是否相等
//	    	//相同   return true;
//	    	//不相同  return false;
//	    }
//		return true;
//	}
}

主函数:

class Main {
	public static void main(String[] agrs) {
		Birds b = new Birds();
		Birds c = new Birds();
		b.setName("abc");
		c.setName("abc");
		System.out.println(b.equals(b));
		System.out.println(b.equals(c));
	}       
}

结果是:

true
true

hashCode()和equals()方法:

public class Birds {
	private int weight;
	private String name;
	public Birds(){
		this.weight = 140;
		this.name = "huanghe";
	}
	
	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public String getName() {
		return name;
	}

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

	public int hashCode(Object obj) {
		int result = 1;
		int prime = 31;
		Birds b = (Birds) obj;
		result = result * prime + weight;
		result = result * prime + ((b.name.equals(name))?0:(b.name).hashCode());
	return result;
	}
    
	public boolean equals(Object obj) {
		if (this == obj) return true;
		if (obj == null) return false;
		Birds b = (Birds) obj;
		if (weight != b.weight) return false;
		if (name != b.name) return false;
		return true;
	}
}

class Main {
	public static void main(String[] agrs) {
		Birds b = new Birds();
		Birds c = new Birds();
		b.setName("abc");
		c.setName("abd");
		System.out.println(b.equals(b));
		System.out.println(b.equals(c));
	}       
}

结果:

true
false


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值