java - 为什么我们必须重写 Java 中的 equals() 方法?

标签 java overriding equals

我对我们覆盖 .equals 方法的原因有些困惑。

例如:

Test test1 = new Test(3);
Test test2 = new Test(3);

//The if comparison does the same thing that the overridden `.equals()` method does.
if(test1.equals(test2)){
    System.out.println("test1 and test2 are true in .equals()");
}

// Override .equals method.
public boolean equals(Object object) {
    if(object instanceof Test && ((Test)object).getValue() == this.t) {
        return true;
    } else {
        return false;
    }
}

我不明白为什么我们必须覆盖 .equals() 方法。

最佳答案

来自文章Override equals and hashCode in Java :

Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.

Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:

many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same

Integer wrapper class overrides equals to perform numerical comparison etc.

关于java - 为什么我们必须重写 Java 中的 equals() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175109/

相关文章:

c# - 为什么返回 false ?新人 ("james") == 新人 ("james")?

java - 为什么 Long equals 在相同值时返回 false?

java - 如何编写一个常规的 equals() 方法,可能与 hashCode() 一起使用?

java - protected 单元测试失败

java - 我可以在具有 JRE 1.6 的系统上运行使用 Java 1.8 构建的应用程序吗?

java - Java中的方法重写-将子类对象分配给父类变量

java - 不重写抽象类中的抽象方法的具体子类

java - JDBC 连接字符串语法和剖析

java - 编程简介 : Conways Game of Life

C#用不同的参数覆盖?