I have some object
class A {
private Long id;
private String name;
public boolean equals(Long v) {
return this.id.equals(v);
}
}
and ArrayList of these objects.
What I want is to be able to check if that list contains some object by object’s field.
For example:
ArrayList<A> list = new ArrayList<A>(); if (list.contains(0L)) {...}
but overrided Equals method is not helps me. What I am doing wrong?
Thank you
UPDATE
And should I override a hashcode() method too?
here’s some code that might demonstrate how it works out:
First, there is an override of the equals(Object o) method. Then there is the override of the hashCode() as well. Also note that the instanceof A check in the equals will ensure that you’re not trying to compare different objects.
That should do the trick! Hope it helped! Cheers 🙂