Override equals() method only of a Java object

android, equals, java, overriding

Solution

You just have to implement it without checking the fields you want to ignore. Don't forget to override the hashode() too.

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((field1 == null) ? 0 : field1.hashCode());
    result = prime * result + ((field2 == null) ? 0 : field2.hashCode());
            ...etc
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    ScanResult other = (ScanResult ) obj;
    if (field1 == null) {
        if (other.field1 != null)
            return false;
    } else if (!field1.equals(other.field1))
        return false;
    if (field2 == null) {
        if (other.field2 != null)
            return false;
    } else if (!field2 .equals(other.field2 ))
        return false;
        }
... etc
}

Problem

I am developing an Android application which makes use of the `ScanResult` object. This object is in the form of: ``` [SSID: __mynetwork__, BSSID: 00:0e:2e:ae:4e:85, capabilities: [WPA-PSK-TKIP][ESS], level: -69, frequency: 2457, timestamp: 117455824743] ``` How would I override only the `equals()` method without creating a customer class which extends it in order to compare only the `SSID`, `BSSID`, `capabilties`, `level` and `frequency` attributes only? In other words, in the `equals` method I want to eliminate the `timestamp` attribute, so that when I compare these two objects, the `equals()` method would return a `true` value: ``` [SSID: __mynetwork__, BSSID: 00:0e:2e:ae:4e:85, capabilities: [WPA-PSK-TKIP][ESS], level: -69, frequency: 2457, timestamp: 117455824743] [SSID: __mynetwork__, BSSID: 00:0e:2e:ae:4e:85, capabilities: [WPA-PSK-TKIP][ESS], level: -69, frequency: 2457, timestamp: 117460312231] ``` Note: When I derive a customer class which extends `ScanResult` I get the following error when I try to implement a constructor: `The constructor ScanResult() is not visible`

Original source