必须首次定义相关对象之间的关系,我发现自己花费整个周末在网上搜索关于equals()
和compareTo()
的干净覆盖实现的信息。找到很少有用的信息后,我决定寻找解决方案。我相信以下方法是compareTo()
方法的解决方案的一种体现。我有一个想法,类似的技术也可以用于equals()
方法。干净的可重写的compareTo()方法?
我的希望是,比我聪明的人可能有时间来验证这些发现并提供有关可能遇到的任何缺陷的反馈。
// 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<Base>
{
/**
* 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;
}
好吧,我想我已经找到了一种方法来解决泰德提出的问题,同时也允许一些额外的自由。一旦我完成了更多的事情,我会发布一个新的解决方案。 – blf 2012-08-01 01:17:03