Short|quick int values comparison

I learned about terminary expression, but what I want is a little different.

I have the following:

int MODE = getMyIntValue();

I do comparison as the following:

if(MODE == 1 || MODE == 2 || MODE == 3) //do something

I would like to know if there is a short way of doing this, I tried something like this but it didn't work:

if(MODE == 1 || 2 || 3) //do something

There is a short|quick way of doing it? I like quick "ifs" because it makes the code more clear, for example, it is more clear this:

System.out.println(MODE == 1 ? text1 : text2):

Than this:

if(MODE == 1) System.out.println(text1):

else System.out.println(text1):

Thanks in advance!

Jon Skeet
people
quotationmark

Well, if you don't mind the boxing hit, you could use a set which you prepared earlier:

// Use a more appropriate name if necessary
private static final Set<Integer> VALID_MODES
    = new HashSet<>(Arrays.asList(1, 2, 3));

...

if (VALID_MODES.contains(mode)) {
}

You could use an int[] and a custom "does this array contain this value" method if you wanted... it would be O(N) or O(log N) for a binary search, but I suspect we're talking about small sets anyway.

people

See more on this question at Stackoverflow