Override equals Code

来源:互联网 发布:cn 域名 编辑:程序博客网 时间:2024/05/14 06:01

我想告诉自己的是:对于所有对象都通用的方法 equals,需要重构。

根据每一个对象特殊的业务判断,我们需要重构这些通用的方法。

因为底层的equals实际上并不满足我们,有的时候,调用后,并不知道里面的真实结果。


Democreen cis = new Democreen("Polish");        String s = "polish";        System.out.println(cis.equals(s) + "  " + s.equals(cis));


console控制台:

DemocreenConnected to the target VM, address: '127.0.0.1:58575', transport: 'socket'Disconnected from the target VM, address: '127.0.0.1:58575', transport: 'socket'true  falseProcess finished with exit code 0




Democreen.java中  

@Override public boolean equals(Object o) {        if (o instanceof Democreen)            return s.equalsIgnoreCase(                    ((Democreen) o).s);        if (o instanceof String)  // One-way interoperability!            return s.equalsIgnoreCase((String) o);        return false;    }

String.java源码:

/**     * Compares this string to the specified object.  The result is {@code     * true} if and only if the argument is not {@code null} and is a {@code     * String} object that represents the same sequence of characters as this     * object.     *     * @param  anObject     *         The object to compare this {@code String} against     *     * @return  {@code true} if the given object represents a {@code String}     *          equivalent to this string, {@code false} otherwise     *     * @see  #compareTo(String)     * @see  #equalsIgnoreCase(String)     */    public boolean equals(Object anObject) {if (this == anObject) {    return true;}if (anObject instanceof String) {    String anotherString = (String)anObject;    int n = count;    if (n == anotherString.count) {char v1[] = value;char v2[] = anotherString.value;int i = offset;int j = anotherString.offset;while (n-- != 0) {    if (v1[i++] != v2[j++])return false;}return true;    }}return false;    }




事实上,我们队实例去比较的时候,可以通过重构equals来提高代码性能跟质量:

public boolean equals(Object obj) {        if (this == obj) {            return true;        }        if (obj != null && obj instanceof Entity) {            Entity tempObj = (Entity) obj;            return new EqualsBuilder()                    .append(getId(), tempObj.getId())                    .isEquals();        } else {            return false;        }    }



是否对称的,传递的,一致的,自反性的,非空性的 ,如果不具备,重新完善,需要自己不断测试优化。



覆盖equals时,总要覆盖 hasCode

见另一篇:覆盖equals时总要覆盖hasCode




0 0
原创粉丝点击