Overriding equals method not working

I looked through a lot of similar questions here and on other sites. However, I cannot get my head to wrap myself around this problem.

I have a class:

public class Event {
    public String Item;
    public String Title;
    public String Desc;

    @Override
    public boolean equals(Object o) {
            return true;
    }
}

I am trying to use this class in ArrayList<Event> events, but I cannot find a way to make it events.contains("item")work. I tried debugging and I found that it doesn't even introduce an overridden method.

What am I doing wrong?

+5
source share
4 answers

This is because you break the symmetry as specified in the contract equals() : if any event equals "item"( which is a string ), "item"it must also be equal to any event.

, , Java, indexOf("item") , .

indexOf() , , ArrayList (. ):

    for (int i = 0; i < size; i++)
        if ("item".equals(elementData[i]))
            return i;

String equals(), , , , , false.

, Event , :

events.contains( new Event("item", "title", "desc") )

, .

+7
0

equals() hashcode(), . , -. Hashmaps . , -.

0

equals, hashCode.

hashCode equals , HashMap. HashMap + linkedList. - hashCode ; List , , -. , ; - List. . , hashCode , . , . , - , .

0
source

All Articles