public ClassA
{
private String firstId;
private String secondId;
public void setFirstId(String firstId) {
this.firstId = firstId;
}
public String
What you are trying to do here in not correct. The 2 objects that you are comparing are not only different objects but are also of different types (ClassA
and ClassB
) which have no relational at all.
Moreover if you try to compare like this
if(bList.contains(clsA))
As your bList
contains objects of type ClassB
and clsA
is of type ClassA
, they will be compared using java.lang.Object
class's equals()
method.
So x.equals(y)
returns true
if and only if x
and y
refer to the same object (x == y
has the value true
).
With the default implementation of Object.equals, two objects of different classes will never be the same.
If you want that behavior, you will need to override .equals in your classes (and .hashcode as well, look at the javadoc).
(Or make a comparator and pass it to your collections).
You can implement a compareTo(ClassB)
or even a compareTo(CommonInterfaceOrSuperclass)
method in each that will do the field-level comparison and return true
if they meet your comparison criteria. You would then need to iterate over your lists and check against each element.
Another alternative is to implement the equals()
/hashcode()
pair, which would, when coded properly, allow your List
to find and compare for equals-ness successfully. Your contains()
test would then work.
Eventhough content is same they are different objects which doesn't satifsy equal condition. You may need to do explicit a.getfirstId().equals(b.getfirsId()) and a.getscondID().equals(b.getSecondId()) by iterating.
The other possibility may be overriding equals and hashcode methods in both POJO classes. Refer this link for equals/hashcode contract.