ITeye博客

Java对象的equals方法

ganglong99 · 2010-07-06 14:46 · java技术 · 编程语言 · Markdown

大家都知道,在Java中,对于对象的比较,如果用“==”比较的是对象的引用,而equals才是比较的对象的内容。

 

一般我们在设计一个类时,需要重写父类的equals方法,在重写这个方法时,需要按照以下几个规则设计:

1、自反性:对任意引用值X,x.equals(x)的返回值一定为true.
2、对称性:对于任何引用值x,y,当且仅当y.equals(x)返回值为true时,x.equals(y)的返回值一定为true;
3、传递性:如果x.equals(y)=true, y.equals(z)=true,则x.equals(z)=true
4、一致性:如果参与比较的对象没任何改变,则对象比较的结果也不应该有任何改变
5、非空性:任何非空的引用值X,x.equals(null)的返回值一定为false

 

例如:

public class People {
    private String firstName;

    private String lastName;

    private int age;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        People other = (People) obj;
        if (age != other.age) return false;
        if (firstName == null) {
            if (other.firstName != null) return false;
        } else if (!firstName.equals(other.firstName)) return false;
        if (lastName == null) {
            if (other.lastName != null) return false;
        } else if (!lastName.equals(other.lastName)) return false;
        return true;
    }
}

 

在这个例子中,我们规定一个人,如果姓、名和年龄相同,则就是同一个人。当然你也可以再增加其他属性,比如必须身份证号相同,才能判定为同一个人,则你可以在equals方法中增加对身份证号的判断!

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。