如何创建Comparator

时间:2014-11-12 21:35:16

标签: java generics comparator

我有通用类,假设

public class MyClass<T extends Comparable<T>> {
    T a;

    MyClass(T x) {
        a = x;
    }

    public String toString() {
        return a.toString();
    }
}

我想让Comparator能够对填充了MyClass元素的集合进行排序。

如果我这样写的话

public class MyComparator implements Comparator<MyClass> {
    public int compare(MyClass o1, MyClass o2) {
        return o1.a.compareTo(o2.a);
    }
}

我收到警告未经检查的电话......

那样编写比较器是否正确
import java.util.Comparator;

public class MyComparator<T extends Comparable<T>> implements Comparator<MyClass<T>> {
    public int compare(MyClass<T> o1, MyClass<T> o2) {
        return o1.a.compareTo(o2.a);
    }
}

1 个答案:

答案 0 :(得分:2)

如果您希望MyClassComparable,那么您可以在不传递Comparator的情况下进行排序,而这可以通过类似的方式完成,

public class MyClass<T extends Comparable<T>> implements
        Comparable<MyClass<T>> {
    T a;

    MyClass(T x) {
        a = x;
    }

    public String toString() {
        if (a == null) return "null";
        return a.toString();
    }

    @Override
    public int compareTo(MyClass<T> o) {
        if (this.a == null) {
            if (o == null || o.a == null) return 0;
            return -1;
        } else if (o == null || o.a == null) return 1;
        return this.a.compareTo(o.a);
    }
}

如果你真的想创建一个MyClassComparator那么它应该看起来像,

public class MyClass<T extends Comparable<T>> {
    T a;

    MyClass(T x) {
        a = x;
    }

    public String toString() {
        if (a == null) return "null";
        return a.toString();
    }
}

public class MyClassComparator<T extends Comparable<T>> implements
        Comparator<MyClass<T>> {
    @Override
    public int compare(MyClass<T> left, MyClass<T> right) {
        if (left == null) {
            if (right == null) {
                return 0;
            }
            return -1;
        } else if (right == null) {
            return 1;
        }
        if (left.a == null) {
            if (right.a == null) {
                return 0;
            }
            return -1;
        } else if (right.a == null) {
            return 1;
        }
        return left.a.compareTo(right.a);
    }
}