If you don't explicitly override .equals()
, they will be compared based solely off of their references (despite not having a equals()
, every object inherits one from Object
). If you only want B
to be compared based off of Sample
, then simply do the following:
@Override
public boolean equals(Object o)
{
if (o istanceof B)
{
return sample.equals(o.sample)
}
return false;
}
Additionally, you should then override hashCode()
(and compareTo()
) to maintain the contract between equals()
and hashCode()
. Hence, you should also have the following:
@Override
public int hashCode()
{
return sample.hashCode();
}
EDIT (in response to comment):
My requirement is first i need to check equals property against "name"
property of Sample. IF names are equals then both objects are equal.
If names are not equals then i need to check for equality against "ID"
property of Sample. How can i do that? Thanks!
Determining whether Samples
are equivalent should be handled in Sample
, by overriding equals()
. If equals()
for Sample
bases off of name
and id
, then you're fine. If you want to compare Samples
in B
differently than they are normally compared, then you're not going to be able to maintain the contract between equals()
and hashCode()
for B
if you use hashCode()
or equals()
from Sample
, which means that your hashCode()
and equals()
for B
should be cannot call equals()
or hashCode()
from Sample
. See this tutorial for how to override based on specific fields.