我正在开发一个使用 ScanResult
的 Android 应用程序目的。该对象的形式为:
[SSID: __mynetwork__, BSSID: 00:0e:2e:ae:4e:85, capabilities: [WPA-PSK-TKIP][ESS], level: -69, frequency: 2457, timestamp: 117455824743]
我如何只覆盖 equals()
方法而不创建扩展它的客户类以便只比较 SSID
、BSSID
、capabilties
、level
和 frequency
属性?换句话说,在 equals
方法中,我想消除 timestamp
属性,这样当我比较这两个对象时, equals()
方法将返回一个 true
值:
[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]
注意:当我派生一个扩展 ScanResult
的客户类时,当我尝试实现构造函数时出现以下错误:构造函数 ScanResult() 是不可见
最佳答案
您只需要在不检查要忽略的字段的情况下实现它。不要忘记也覆盖 hasode()。
@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
}
关于java - 仅覆盖 Java 对象的 equals() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885991/