Java Object Comparison – Object Comparison for Equality in Java

comparisonequalityjavaobject

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?

Best Answer

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).

Related Question