Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding equals method doesn't work

I've been browsing a lot of similar questions in here and on other sites. Still I can't seem to get my head wrapped 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'm trying to use this class in an ArrayList<Event> events but I can't find a way to get events.contains("item") to work. I have tried debuging and I've found that it doesn't even enter the overridden method.

What am I doing wrong?

like image 882
CornflakesDK Avatar asked May 26 '12 10:05

CornflakesDK


1 Answers

That's because you're breaking symmetry as specified in the contract of equals(): if any event equals to "item" (which is a String), "item" should also be equal to any event.

Actually, what Java does is to call indexOf("item") on your list, and check if it is positive.

Now, indexOf() works like this in an ArrayList for instance (see complete source code here):

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

So basically it is the String's equals() method which is called here, not your one which is returning false of course.

Solve this issue by simply specifying an Event parameter to the function, like:

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

Note that you'll have to create a proper constructor for your class ot initialize the members.

like image 123
rlegendi Avatar answered Oct 06 '22 00:10

rlegendi