Overrides only the equals() method of Java objects… here is a solution to the problem.
Overrides only the equals() method of Java objects
I’m working on a ScanResult
that uses Android application purpose. The object has the form:
[SSID: __mynetwork__, BSSID: 00:0e:2e:ae:4e:85, capabilities: [WPA-PSK-TKIP][ESS], level: -69, frequency: 2457, timestamp: 117455824743]
How do I override only the equals()
method without creating a client class that extends it so that only SSID
, BSSID,
capabilties
, level
, and frequency
properties are compared? In other words, in the equals method, I want to eliminate the timestamp
property so that when I compare the two objects, the equals()
method will 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 client class that extends ScanResult, I get the following error when I try to implement the constructor: The constructor ScanResult() is not visible
Solution
You just need to implement it without checking the fields you want to ignore. Don’t forget to override hasode() as well.
@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
}