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

如何重写ArrayList中特定元素的hashCode()与equals()方法?

Hey there! Let's clear up the confusion first—you're mixing up two totally different things here: the hashCode() of your Team objects and the hashCode() of the new String you're creating.

Let's Break Down the Misunderstanding

When you run anotherArrayList.add(definingString + rockets.teamName);, you're not modifying the original Team object at all. You're creating a brand-new String instance that combines your fixed text with the teamName of the Rockets team. That new string has its own independent hashCode(), which has zero to do with the Team object's hash code. The Rockets Team instance itself hasn't changed, so its hashCode() stays the same (even if you use the default implementation, which is based on object identity, not field values).

Fixing Your Core Goal: Stable Hash Codes for Team Objects

If your real aim is to ensure Team objects have consistent hash codes (and work correctly in hash-based collections like HashSet), here's how to do it properly:

  1. First, define what makes two Team objects equal
    For a team, equality should almost always tie to a unique identifier—like teamName (assuming team names are unique in your league).

  2. Always override equals() and hashCode() together
    A golden rule: if two objects are equal (per equals()), they must have the same hashCode(). Base both methods on the same set of fields to avoid bugs.

Here's the corrected Team class with proper overrides:

import java.util.Objects;

class Team {
    private String teamName; // Encapsulate fields for better control

    public Team(String teamName) {
        this.teamName = teamName;
    }

    // Getter to access the team name (since it's private)
    public String getTeamName() {
        return teamName;
    }

    // Optional setter if you need to update the team name later
    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // Same object? Equal
        if (o == null || getClass() != o.getClass()) return false; // Wrong type? Not equal
        Team team = (Team) o;
        return Objects.equals(teamName, team.teamName); // Compare the unique field
    }

    @Override
    public int hashCode() {
        return Objects.hash(teamName); // Hash based on the same field used in equals()
    }
}

Key Notes to Remember

  • If you modify the teamName (via the setter), the Team's hashCode() will change. This is important: if you put the Team in a HashSet or HashMap, changing the field used for hashing will break the collection's ability to find the object later.
  • If you need an unchanging hash code for Team objects even when fields are modified, base the hashCode() on an immutable field (like a unique ID set once in the constructor and never updated).

Back to Your Original Code

The string you're adding to anotherArrayList is a separate, immutable object. You can't override its hashCode() (since String is a final class), but you don't need to—if you're trying to link the string to the Team's identity, store the Team object itself in the list instead of a derived string, or store a pair of Team and the string.

内容的提问来源于stack exchange,提问作者Paris B. G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:01:46