我有通用类,假设
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);
}
}
答案 0 :(得分:2)
如果您希望MyClass
为Comparable
,那么您可以在不传递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);
}
}