public ClassA
{
private String firstId;
private String secondId;
public void setFirstId(String firstId) {
this.firstId = firstId;
}
public String getFirstId() {
return id;
}
public void setSecondId(String secondId) {
this.secondId = secondId;
}
public String getSecondId() {
return secondId;
}
}
public ClassB
{
private String firstId;
private String secondId;
public void setFirstId(String firstId) {
this.firstId = firstId;
}
public String getFirstId() {
return id;
}
public void setSecondId(String secondId) {
this.secondId = secondId;
}
public String getSecondId() {
return secondId;
}
}
I have the above 2 classes(POJOs) which are absolutely the same (except for the name of course) which I am adding to two arraylists: aListA and aListB. I need to compare if the two objects are the same. If they are same I need to add them to another list(commonList) and if they happen to be the different, I need to add them to another list(differentList). I have written the following code:
ClassA clsA = null;
public ArrayList genCommonList(aList, bList)
{
for(int i = 1; i<aList.size(); i++)
{
clsA = new ClassA;
Object obj = aList.get(i);
clsA = (ClassA)obj;
if(bList.contains(clsA)
{
genCommonList.add(clsA);
}
}
public ArrayList genDifferentList(aList, bList)
{
for(int i = 1; i<aList.size(); i++)
{
clsA = new ClassA;
Object obj = aList.get(i);
clsA = (ClassA)obj;
if(!bList.contains(clsA)
{
genDifferentList.add(clsA);
}
}
My problem is that even when the data(both variables, firstId and secondID) in the 2 different POJOs are the same, they get put in the different list. That means the objects are not being compared for equality using the contains() method of the ArrayList class. I dont want to get the data from each variable inside the POJO and compare. Is there a way to compare the POJOs for both variables and be determined as either equal or unequal?
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.