java compareto重写_java-可以重写的compareTo()方法?

本文探讨了在Java中重写equals()和compareTo()方法时可能遇到的问题。作者通过一个Base类示例展示了compareTo()方法的实现,并指出该实现存在一个问题:当比较不同子类实例时,可能会违反比较通用契约。作者建议阅读相关文章以了解更多关于比较对象时的细节和潜在陷阱。
摘要由CSDN通过智能技术生成

必须第一次定义相关对象之间的关系,我发现自己花了整个周末在网络上搜寻有关equals()和compareTo()的可重写实现的信息.找到了很少的有用信息后,我决定寻找解决方案.我相信以下是用compareTo()方法表示的解决方案.我的想法是,类似的技术也可能适用于equals()方法.

我希望比我更聪明的人可能有时间验证这些发现并提供有关可能遇到的陷阱的反馈.

// The name chosen for the following class shell ("Base") is intended to

// portray that this compareTo() method should be implemented on a base class

// as opposed to a subclass.

public class Base

implements Comparable

{

/**

* Compares this Base to the specified Object for semantic ordering.

*

* @param other The Object to be compared.

*

* @return An int value representing the semantic relationship between the

* compared objects. The value 0 is returned when the two objects

* are determined to be equal (as defined by the equals method).

* A positive value may be returned if the "other" object is a

* Base and the "exact types" comparison determines this Base to

* have a higher semantic ordering than the "other" object, if the

* "other" object is not a Base, or if the "other" object is a

* subclass of Base who's compareTo method determines itself to

* have a lower semantic ordering than this Base. A negative value

* may be returned if the "other" object is a Base and the

* "exact types" comparison determines this Base to have a lower

* semantic ordering than the "other" object or if the "other"

* object is a subclass of Base who's compareTo method determines

* itself to have a higher semantic ordering than this Base.

*/

public int compareTo(Base other)

{

int relationship = 0;

if (other == null)

throw new NullPointerException("other: Cannot be null.");

if (!this.equals(other))

{

if (this.getClass() == Base.class)

{

if (this.getClass == other.getClass())

relationship = // Perform comparison of exact types;

else

relationship = -1 * other.compareTo(this);

}

else

relationship = 1;

}

return relationship;

}

解决方法:

这是行不通的.考虑直接扩展Base且实例永远不相等的两个类A和B.然后两个实例Base a = new A();并且基数b =新的B().由于this.getClass()== Base.class对于a和b均为假,因此将出现a.compareTo(b)== 1以及b.compareTo(a)== 1的情况.对于所有可比较的x和y,sgn(x.compareTo(y))== -sgn(y.compareTo(x))的通用合同.

对于比较对象(尤其是测试子类之间的相等性)所涉及的一些微妙之处,我建议使用this excellent article.

标签:compareto,equals,java

来源: https://codeday.me/bug/20191201/2077417.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值