Compare objects in LinkedList.contains()

后端 未结 6 1735
梦谈多话
梦谈多话 2020-12-06 12:00

I want to be able to have LinkedList.contains() return true for a custom comparator.

Suppose that I have 1 LinkedList and 2 objects

LinkedList

        
6条回答
  •  猫巷女王i
    2020-12-06 12:21

    You need to override the .equals(Oject) and the .hashCode() methods in the MyObject class (hashCode isn't needed for the List... but when you overrite equals the contract says you have to override hashCode).

    Essentially what the contains does is this:

    for(each item in the list)
    {
        if(theCurrentItem.equals(theItemYouAreLookingFor))
        {
            return (true);
        }
    }
    
    return (false);
    

    Take a look at the documentation for Object (for equals and hashCode) here

    Also a really good book to read is Effective Java

提交回复
热议问题