Reputation:
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
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
Reputation: 18364
From the JavaDoc:
boolean contains(Object o)
Returnstrue
if this list contains the specified element.
More formally, returnstrue
if and only if this list contains at least one elemente
such that(o==null ? e==null : o.equals(e))
.
Specified by:contains
in interfaceCollection<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