I have created one class name like Test and have overriden its equals() and hashcode() methods and then created its 2 objects like below -
Test obj1 = new Test ();
Test obj2 = new Test ();
and now performaing following operation -
obj1.equals(obj2); // I am getting **True** that is fine.
But if i change i code bit like below -
Set<Test> testSet = new Set<Test>();
testSet.add(obj1);
Print : testSet.contains(obj2); // It is returning **False**....
I debug the code and found in this case HashCode() method is getting called but equals() is not being called. HashCode is some for both the object.
As per my understanding it should return True.
Modified --
My code is below -
Class
public Class DMAClipLevelWrapperForExport {
public String businessUnit {get; set;}
public String dmaType {get; set;}
public Decimal tcvMin {get; set;}
public Decimal tcvMax {get; set;}
/*
* Overriding equals
*/
public Boolean equals(DMAClipLevelWrapperForExport obj) {
if(obj != null){
if(obj.tcvMin == this.tcvMin && obj.tcvMax == this.tcvMax) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/*
* Overriding hashCode
*/
public Integer hashCode() {
return this.tcvMin.intValue() + this.tcvMax.intValue();
}
}
Code written to test
Set<DMAClipLevelWrapperForExport> dmaClipLevelWrapperForExport = new Set<DMAClipLevelWrapperForExport>();
DMAClipLevelWrapperForExport one = new DMAClipLevelWrapperForExport();
one.businessUnit = 'APACC';
one.dmaType = 'CES';
one.tcvMin = 0;
one.tcvMax = 500000;
dmaClipLevelWrapperForExport.add(one);
DMAClipLevelWrapperForExport clipLevel = new DMAClipLevelWrapperForExport();
clipLevel.businessUnit = 'APACC';
clipLevel.dmaType = 'CES';
clipLevel.tcvMin = 0;
clipLevel.tcvMax = 500000;
if(dmaClipLevelWrapperForExport.contains(clipLevel)) {
system.assert(false, 'Object found in list');
} else {
system.assert(false, 'Object not found in list');
}
Always getting 'Object not found in list'.
Can anyone explain what is wrong in this code please?
Thanks for reply