初めて、関連するオブジェクト間の関係を定義しなければならなかったため、 と の完全にオーバーライド可能な実装に関する情報を求めて、週末全体を Web で探し回っていることに気付きまし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;
}