Override equals Code

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

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

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


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


console控制台:

Democreen
Connected 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  false

Process 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值