CornflakesDK CornflakesDK - 1 year ago 73
Java Question

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;

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
to work. I have tried debuging and I've found that it doesn't even enter the overridden method.

What am I doing wrong?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download