What I am doing wrong?
You are not overriding. You are overloading.
The contains
method calls the equals
method with signature equals(Object)
, so this (new) method that you've added won't be called.
The other problem is that your equals
method has the wrong semantics for contains
. The contains
method needs to compare this
against an object that could be a member of the list. Your list does not contain Long
objects. It contains objects of type A
.
Now you might get away with this ... if you use raw list types ... but what you are trying to do is a violation of the API contract, and bad practice. A better solution is to iterate and test the elements of the list explicitly.
And should I override a hashcode() method too?
If you override equals(Object)
then you should also override hashcode()
.
It won't make any difference here, but it is essential if you ever put your A
objects into hashed data structures. And since you don't know what the next guy is going to do with your code, it is good practice to make sure that equals(Object)
and hashCode()
have compatible semantics.