java 如何覆盖特定 arrayList 项的 hashcode() 和 equals()

java How To override the hashcode() and equals() of a specific arrayList item

好的,所以我的问题很简单。我搜索了 Whosebug、google 和 JavaDocs,但似乎找不到我的具体问题的答案。

据我了解(在这里归结为基础知识),每个对象都有一个 hashCode() 作为唯一标识符。我们将以此为例...

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

    class NBALeague {
        ArrayList<Team> teamsInALeague = new ArrayList<>();
        teamsInALeague.add(new Team("Rockets"));
        teamsInALeague.add(new Team("Warriors"));
        teamsInALeague.add(new Team("Cavaliers"));
        teamsInALeague.add(new Team("76ers"));
    //each unique team when instantiated is assigned a hashCode!

        //now when I change the objects (or add to them rather) they are then 
        //each given a new hashCode()

          public void buildASchedule(){
             Team rockets = teamsInALeague.get(0);
             Team warriors= teamsInALeague.get(1);
             Team cavaliers= teamsInALeague.get(2);
             Team philly= teamsInALeague.get(3);

             String definingString = "This Team is Called: ";

             ArrayList anotherArrayList = new ArrayList();

             anotherArrayList.add(definingString + rockets.teamName);
             //Moving an object from one array list to another doesnt affect
             //its hashcode(), but adding a string to the object does

既然 anotherArrayList.get(0) 有了全新的哈希码,我该如何覆盖它?

我知道我必须覆盖 hashcode()equals() 方法以确保在放入 HashSet 时,该集合可以识别重复项,但是因为这些新的哈希码是在向对象添加一个字符串我不知道如何覆盖哈希码。通常我会通过 Team class 覆盖这两种方法,但同样不会起作用,因为更改对象会创建新的哈希码。请有人帮忙!!!

您似乎有两个误解:hashCode 实际上是什么,以及 + 运算符是如何工作的。

我将首先解决后者。除了赋值 (=) 之外,当您在对象上应用运算符时,它不会以任何方式更改对象。语句

anotherArrayList.add(definingString + rockets.teamName);

不会以任何方式改变或影响 rockets 变量。它没有 "change the hashCode" 或任何其他关于它的东西,它只是复制 rockets.teamName 的值,将它与其他东西连接起来,并创建一个全新的对象。那个全新的对象将是一个字符串,因此您无论如何都不能将它添加到列表中。

现在,关于 hashCode。对象不是 "assigned a hashCode" 或类似的东西。 hashCode() 没有什么特别的、神奇的或自动的,它只是一个 return 是一个整数的方法。它 return 是你告诉它 return 的内容,如果你不覆盖它,默认实现 return 是一个 永远不会 改变的数字对于给定的对象。

如果您用另一个对象替换该对象,例如将另一个Team放在列表中的那个位置,那么该对象将有自己的hashCode可能与第一个不同。但只需使用对象或其字段之一 不会以任何方式影响它。