简体   繁体   中英

overriding equals and hashcode method, returning false

I have wifi signals using ScanResult class, I am keeping all the signal in arraylist of object containing all the fields such as ssid, bssid, dbm etc.

I want to check if two wifi signal objects are equal or not, so I override my equal and hashcode method, but it is returning false in some case even though the fields are same. I double checked the fields.

Here is my equals and hashcode method in property class, please tell me if I am doing anything wrong..

@Override
public boolean equals(Object obj) {
    if(this == obj)
        return true;
    if((obj == null) || (obj.getClass() != this.getClass()))
        return false;

    property sig = (property) obj;

    if(sig != null) {
        if (sig.ssid != null && sig.type != null && sig.bssid != null) {
            if (sig.ssid.equals(ssid) && sig.dbm == dbm && sig.type.equals(type) && sig.bssid.equals(bssid)) {
                return true;
            }
        }
    }
    return false;
}

@Override
public int hashCode() {
    final int prime = 31;
    if (ssid != null) {
        return ((ssid.hashCode() + type.hashCode() + dbm + bssid.hashCode() + freq) * prime);
    }
    return -1;
}

Use

sig.dbm.equals(dbm)

instead of

sig.dbm == dbm

if dbm is not primitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM