我为我的对象定义了4个比较器,如下所示:
public static Comparator<mObject> comp0 = new Comparator<mObject>() {
@Override
public int compare(mObject l, mObject r) {
...compare
}
};
public static Comparator<mObject> comp1 = new Comparator<mObject>() {
@Override
public int compare(mObject l, mObject r) {
...compare
}
};
public static Comparator<mObject> comp2 = new Comparator<mObject>() {
@Override
public int compare(mObject l, mObject r) {
...compare
}
};
public static Comparator<mObject> comp4 = new Comparator<mObject>() {
@Override
public int compare(mObject l, mObject r) {
...compare
}
};
现在我想用4个比较器创建一个数组,像这样:
public final static Comparator<mObject>[] Object_comparators = { comp0,
comp1,
comp2,
comp3};
但是Eclipse强调了{..}之间的所有内容,就像它是一个错误一样。为什么这样做,我该如何解决呢?
最佳答案
您不能使用参数化的泛型类型创建类的数组。
如果您不介意丢失类型安全性,则可以执行以下操作:
Comparator[] list = new Comparator[4];
但是我的首选策略是使用
List
:List<Comparator<mObject>> list = Arrays.asList(comp0, comp1, comp2, comp3);