覆盖equals()方法只有一个Java对象的 [英] Override equals() method only of a Java object

查看:190
本文介绍了覆盖equals()方法只有一个Java对象的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个Android应用程序,这使得使用 ScanResult 对象。此对象是在形式:

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]

我怎么会只覆盖了等于()方法,而无需创建延伸它以比较仅 SSID BSSID capabilties 级别频率仅属性?换句话说,在等于方法,我想消除时间戳属性,这样,当我比较这两个对象中,等于()方法将返回一个真正值:

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]

注意::当我得到延伸客户类 ScanResult 我收到以下错误,当我试图实现一个构造函数:构造ScanResult()是不可见

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

推荐答案

您只需要实现它不检查你想忽略的领域。不要忘了覆盖hashode()了。

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
}

这篇关于覆盖equals()方法只有一个Java对象的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆