【问题标题】:how to implement comparator when compare function is used in the same class [closed]在同一个类中使用比较函数时如何实现比较器[关闭]
【发布时间】:2013-12-05 12:37:43
【问题描述】:

如果一个类实现了比较器,我们如何定义比较函数?

public int compare(classname c1, classname c2) {
    // c1 has to be this.how can we use it?
}

【问题讨论】:

标签: java


【解决方案1】:

您使用 java 泛型,内置于 Comparator 接口。

public class MyClass implements Comparator<MyClass>

【讨论】:

    【解决方案2】:
    public int compare(classname c1, classname c2) {
        if (cl.something > c2.something)
            return 1;
        else if (c1.something == c2.something)
            return 0;
        else
            return -1;
    }
    

    编辑:可比较

    public class classname implements Comparable<classname>{
        int something;
    
        public int compareTo(classname c2){
            if (this.something > c2.something)
                return 1;
            else if (this.something == c2.something)
                return 0;
            else
                return -1;
        }
    }
    

    【讨论】:

    • c1 是当前对象,它是 ..它的 THIS..我们如何将它作为参数之一传递?
    • 在这种情况下,您应该使用 compareTo() 并使类 Comparable。查看我的编辑
    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多