java中的比较运算符对象

时间:2012-03-12 17:29:00

标签: java operators operator-keyword

Java中是否存在这些比较运算符(<,< =,==,> =,>,!=)的对象表示?

E.g。用例:

void filterHotel( Object operator, float rating ) {

    String query = "SELECT hotel.name from hotel where hotel.rating " + 
operator.toString() + rating;    
    // execute query
}

2 个答案:

答案 0 :(得分:3)

即可。但是编写起来很容易,考虑将enum与自定义方法一起使用:

public enum Operator {
    EQUAL("=="),
    NOT_EQUAL("<>"),
    GREATER_THAN(">"),
    GREATER_THAN_OR_EQUAL(">="),
    LESS_THAN("<"),
    LESS_THAN_OR_EQUAL("<=");

    private final String representation;

    private Operator(String representation) {
        this.representation = representation;
    }

    public String getRepresentation() {
        return representation;
    }
}

通过,例如Operator.LESS_THAN并使用operator.getRepresentation()提取实际运算符。

另外,请确保用户不能使用任意字符串代替operator以避免

答案 1 :(得分:1)

内置任何内容,但您可以定义一个enum来实现这一目的:

public enum ComparisonOperator {
    LT("<"), LE("<="), EQ("=="), NE("<>"), GE(">="), GT(">");

    ComparisonOperator(String symbol) { this.symbol = symbol; }
    private final String symbol;
    public String toSymbol() { return symbol; }
}

然后:

void filterHotel(ComparisonOperator operator, float rating) {

    String query = "SELECT hotel.name from hotel where hotel.rating " + 
        operator.toSymbol() + rating;    
    // execute query
}