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

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

解决方法:

这是行不通的.考虑直接扩展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.

上一篇:在C#中从排序的字典中获取数据时出错


下一篇:Java,如何使用compareTo对Arraylist进行排序