2 Aralık 2014 Salı

[Java] multiple || "or" statements


When I used to code, I had to compare a value with multiple other values in order to check if one of the values match with the compared one. It became something like below:

        String equation = "A";
        if (equation.equals("A") || equation.equals("C") || equation.equals("B") || equation.equals("D")) {
            // do something.
        }

Ugly and stinky code. I made something simple and my code became shorter and readable.

    public static <T> boolean isContains(T in, T... conditions) {
        for (T iterationItem : conditions) {
            if ((iterationItem.equals(in)))
                return true;
        }
        return false;
    }


String equation = "A";
if(isContains(equation, "A", "C", "B", "D")){
    // do something.
}

Happy coding.

Hiç yorum yok:

Yorum Gönder