由于必须第一次定义相关对象之间的关系,我发现自己花了整个周末在网上搜索有关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<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;
}