自定义对象的比较
如果使用“==”则比较的是两个对象的地址信息,但是我们正常认为两个对象的所有属性值相等两个对象就相等。
package com.baidu.vo;
import java.io.Serializable;
//部门表简单Java类
public class Dept implements Serializable {
private Integer deptno;
private String dname;
public Dept(){};
public Dept(Integer deptno, String dname) {
this.deptno = deptno;
this.dname = dname;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
}
package com.CoderLB;
import com.baidu.vo.Dept;
public class Test {
public static void main(String[] args) {
Dept dept1 = new Dept(1002,"市场部门");
Dept dept2 = new Dept(1002,"市场部门");
if(dept1.getDeptno().equals(dept2.getDeptno())&&dept1.getDname().equals(dept2.getDname())){
System.out.println("两个对象相等");
}else{
System.out.println("两个对象不相等");
}
}
}
//输出:两个对象相等
上述实现了两个对象的比较,但是是在主方法中的比较,一般要求主方法中不要出现逻辑业务代码,主方法就是一个客户端,最好将比较的过程交给Dept完成。
package com.baidu.vo;
import java.io.Serializable;
//部门表简单Java类
public class Dept implements Serializable {
private Integer deptno;
private String dname;
public Dept() {
}
public Dept(Integer deptno, String dname) {
this.deptno = deptno;
this.dname = dname;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
//定义对象的比较方法
public void equals(Dept dept) {
if (this == dept) {
System.out.println("二者完全一致");
}
if (dept == null) {
System.out.println("输入为空");
}if(this.getDeptno().equals(dept.getDeptno())&&this.getDname().equals(dept.getDname())){
System.out.println("二者内容相同");
}else {
System.out.println("二者不同");
}
}
}
package com.CoderLB;
import com.baidu.vo.Dept;
public class Test {
public static void main(String[] args) {
Dept dept1 = new Dept(1001,"市场部门");
Dept dept2 = new Dept(1002,"市场部门");
dept1.equals(dept2);
}
}
//输出:二者不同
小结
- 自定义对象的比较只能两个对象都是同哟个类创建的才有意义。
- 比较的时候要判断是否是空对象。
- 比较的时候要判断是不是和自己进行比较。