正在使用比较器" offtopic"糟糕的java风格?

时间:2013-09-20 10:38:02

标签: java coding-style

感谢@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代码,我做了比较 我需要这个代码三次为grater,相等更少但我不想复制代码所以我做了一个参数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);

1 个答案:

答案 0 :(得分:3)

如果那些不是“真正的”比较器,并且您只能从自己的代码中调用它们,那么您也可以定义自己的接口。这对我来说似乎更清洁。