感谢@Thilo,我让这样的界面变得疯狂:
public interface compareOp<T> {
public boolean compare(T op1, T op2);
}
和“实施者”:
private static final compareOp<Integer> GreaterThan = new compareOp<Integer>() {
@Override
public boolean compare(Integer x, Integer y) {
if (x > y)
return true;
return false;
}
};
private static final compareOp<Integer> SameThan = new compareOp<Integer>() {
@Override
public boolean compare(Integer x, Integer y) {
if (x == y)
return true;
return false;
}
};
private static final compareOp<Integer> LessThan = new compareOp<Integer>() {
@Override
public boolean compare(Integer x, Integer y) {
if (x < y)
return true;
return false;
}
};
我已经写了 som 代码,我在其中进行了比较,我需要此代码三次,以获得更小,但我不想复制代码,所以我做了一个参数 comp 类型比较器并检查:
if (comp.compare(output1[i][n1], output2[j][n2]) == 0)
我的比较器不能用于正常排序,因为它们违反了 -1,0,1 规则,但我不将它们用于其他事情
这是关于 Java 规则的不良风格吗?
这是我的比较器的代码:
private static final Comparator<Integer> GreaterThen = new Comparator<Integer>() {
@Override
public int compare(Integer x, Integer y) {
if (x > y)
return 0;
return -1;
}
};
private static final Comparator<Integer> SameThen = new Comparator<Integer>() {
@Override
public int compare(Integer x, Integer y) {
if (x == y)
return 0;
if (x > y)
return 1;
return -1;
}
};
private static final Comparator<Integer> LessThen = new Comparator<Integer>() {
@Override
public int compare(Integer x, Integer y) {
if (x < y)
return 0;
return 1;
}
};
这就是我使用它们的方式:
new Helpers().subSetsCompared(input1, 3, input2, 4, GreaterThen);
new Helpers().subSetsCompared(input1, 3, input2, 4, SameThen);
new Helpers().subSetsCompared(input1, 3, input2, 4, LessThen);