You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java对象比较练习求助:equals方法实现错误排查

Fixing the Person Class equals() Method

Hey there! Let's fix that equals method issue you're having. Right now your equals only checks if both references point to the exact same object, which isn't enough for most equality checks in Java. Here's how to properly implement it, plus a few extra tips to make it solid:

Step 1: Correct the equals() Implementation

Your current method only checks reference equality. We need to compare the actual properties of the Person objects to determine if they're logically equal. Here's the revised code:

import java.util.Objects;
public class Person {
    private String name;
    private SimpleDate birthday;
    private int height;
    private int weight;

    public Person(String name, SimpleDate birthday, int height, int weight) {
        this.name = name;
        this.birthday = birthday;
        this.height = height;
        this.weight = weight;
        // Remove the hashCode() call here—it's unnecessary; hashCode is computed on demand
    }

    // Getters remain the same
    public String getName(){
        return this.name;
    }

    public SimpleDate getBirthday(){
        return this.birthday;
    }

    public Integer getHeight(){
        return this.height;
    }

    public Integer getWeight(){
        return this.weight;
    }

    @Override
    public boolean equals(Object compared){
        // 1. Quick check if references are identical
        if (this == compared) {
            return true;
        }

        // 2. Verify compared object is not null and is a Person instance
        if (!(compared instanceof Person)) {
            return false;
        }

        // 3. Cast to Person type for field comparison
        Person comparedPerson = (Person) compared;

        // 4. Compare all relevant fields safely
        return Objects.equals(this.name, comparedPerson.name) &&
               Objects.equals(this.birthday, comparedPerson.birthday) &&
               this.height == comparedPerson.height &&
               this.weight == comparedPerson.weight;
    }

    // Step 2: Override hashCode() to match equals()
    @Override
    public int hashCode() {
        return Objects.hash(name, birthday, height, weight);
    }
}

Key Explanations

  • Reference Check First: This is a performance optimization—if the two objects are the exact same reference, we can return true immediately without checking all fields.
  • Null & Type Validation: We ensure we're comparing a Person object to another Person (not null or a different type), which avoids runtime errors and incorrect equality checks.
  • Safe Field Comparison: Using Objects.equals() handles null values gracefully (e.g., if name is null for one object but not the other, it won't throw a NullPointerException). For primitive fields like height and weight, we can use direct == comparison.
  • Hashcode Consistency: Java's contract requires that if two objects are equal (per equals()), they must have the same hashCode(). The Objects.hash() method simplifies creating a consistent hash by combining the hash codes of all relevant fields. Also, remove that unnecessary hashCode() call from your constructor—it doesn't serve any purpose there.

Critical Note About SimpleDate

For the birthday comparison to work correctly, your SimpleDate class must also have a properly implemented equals() and hashCode() method. If it doesn't, the code will only check if the birthday references point to the same object, not if the date values are equal.

内容的提问来源于stack exchange,提问作者Cat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:42:48