即使两个对象的内容相同,equals()也可能返回false吗?

时间:2014-08-20 11:53:14

标签: java

即使两个对象的内容相同,equals()也可以返回false吗? 如果是,我如何在以下代码中证明: 在下面的例子中,p1.equals(p2)如何导致'false' 我知道错误实现的equals()和hashcode()方法可能导致这种情况,但想知道在什么数据集下会出现相等的失败。

public class Equalitytest {

    public static void main(String[] args) {

    Person p1 = new Person("abc",12);
    Person p2 = new Person("abc",12);

//Is there any way which results in  
// assert p1.equals(p2) == false  
//What dataset will will satisfy the assertion to false?

    }

    public class Person {
    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if (this.age != other.age) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }
    }

1 个答案:

答案 0 :(得分:-2)

你可以像这样覆盖equals()方法

@Override
public boolean equals(Object obj) {
return false ;
}

这是合法的。