user3352135
user3352135

Reputation:

equals for arrayList is not being called, ever

I have Client class, which contains ArrayList of Category objects. So, when I want to make sure that some sort of Category object exists (by that I mean Categories name is the same), I call .contains() method for array list of categories.

I overrriden .equals() method in Category class like so:

@Override
public boolean equals(Object object) {
    boolean isEqual = false;
    Log.d("Category", "IT WORKS");
    if (object != null && object instanceof Category) {
        isEqual = (this.name == ((Category) object).getName());
    }

    return isEqual;
}

But in the console I am able to see, that equals method is never being called. Why is this happening?

Upvotes: 1

Views: 376

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201527

I tested it like so,

static class Category {
    public Category(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (o != null && o instanceof Category) {
            return this.getName().equals(((Category) o).getName());
        }
        return false;
    }
}

public static void main(String[] args) {
    List<Category> al = new ArrayList<>();
    al.add(new Category("test"));
    System.out.println(al.contains(new Category("test")));
}

Output is

true

Upvotes: 2

Nivas
Nivas

Reputation: 18364

From the JavaDoc:

boolean contains(Object o)
Returns true if this list contains the specified element.
More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
Specified by: contains in interface Collection<E>

So, when you call list.contains(o), the equals is called on o and not on the element of the list.

Something like

boolean contains(o)
{
    for every e in list loop
        if o.equals(e)
            return true
    end loop
    return false
}

Depending on how you are calling contains and the parameter to it, the equals being called may be in a completely different class (of the object in the parameter).

Upvotes: 1

Related Questions