.Contains() method not calling Overridden equals method

前端 未结 3 1677
情书的邮戳
情书的邮戳 2020-12-28 15:07

I am having an issue where I make an ArrayList of Foo objects, I override the equals method, and I cannot get the contains method to call the equals method. I have tried ove

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 16:03

    You should implement hashCode

    @Override
    public int hashCode() {
        return id.hashCode();
    }
    

    even though the contains works for ArrayList without it. Your big problems are that your equals expects String, not Foo objects and that you ask for contains with Strings. If the implementation asked each eject in the list if they were equal to the string you send, then your code could work, but the implementation asks the string if it is equal to your Foo objets which it of course isn't.

    Use equals

    @Override
    public boolean equals(Object o){
        if(o instanceof Foo){
            String toCompare = ((Foo) o).id;
            return id.equals(toCompare);
        }
        return false;
    }
    

    and then check contains

    System.out.println(fooList.contains(new Foo("ID1")));
    

提交回复
热议问题