您的位置:首页 > 编程语言 > Java开发

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

2014-08-09 08:17 501 查看
   ==操作符判断的是地址是否相等,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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java
相关文章推荐