Java – the correct hashcode is required when comparing an object with an unordered integer pair as a variable

I'm in 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. When they have the same building ID, they are the same

So they need to be equal in the following two directions:

BuildingPair(1,2) vs BuildingPair(2,1) 
BuildingPair(1,2) vs BuildingPair(1,2)
BuildingPair(2,1) vs BuildingPair(1,2)

I think the equals method is OK, but hashcode is wrong

Solution

Whether through a, B or B, a, you need to calculate something with the same result There may be more subtle solutions, but I may choose:

@Override
public int hashCode() {
    return mBA * mBB;
}

Or anything else that uses commutative operators

Alternatively, you can change the constructor so that it always stores min (a, b) in M (m, b) and max (a, b) in MBB – then you can simplify the comparison code and keep the current hash code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>