I have a class
final class BuildingPair {
int mBA;
int mBB;
public BuildingPair(int pBuildingA,int pBuildingB) {
mBA = pBuildingA;
mBB = pBuildingB;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + mBA;
result = prime * result + mBB;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BuildingPair other = (BuildingPair) obj;
if ((mBA==other.mBA&&mBB==other.mBB)||(mBA==other.mBB&&mBB==other.mBA)) return true;
return false;
}
}
I want to compare two objects , and when both have the same buildings ids they are equal
so they need to be equal in both directions when :
BuildingPair(1,2) vs BuildingPair(2,1)
BuildingPair(1,2) vs BuildingPair(1,2)
BuildingPair(2,1) vs BuildingPair(1,2)
i think equals method is ok, but hashcode is wrong.
You need something that computes the same result whether passed
A,BorB,A. There may be far more subtle solutions, but I’d probably just go for:Or anything else which uses an operator that is commutative.
Alternatively, you could change your constructor so that it always stores
min(a,b)inmBAandmax(a,b)inmBB– you can then simplify your comparison code and keep your hash code as it currently is.