Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a way to test for enum value in a list of candidates? (Java)
    primarykey
    data
    text
    <p>This is a simplified example. I have this enum declaration as follows:</p> <pre><code>public enum ELogLevel { None, Debug, Info, Error } </code></pre> <p>I have this code in another class:</p> <pre><code>if ((CLog._logLevel == ELogLevel.Info) || (CLog._logLevel == ELogLevel.Debug) || (CLog._logLevel == ELogLevel.Error)) { System.out.println(formatMessage(message)); } </code></pre> <p>My question is if there is a way to shorten the test. Ideally i would like somethign to the tune of (this is borrowed from Pascal/Delphi):</p> <pre><code>if (CLog._logLevel in [ELogLevel.Info, ELogLevel.Debug, ELogLevel.Error]) </code></pre> <p>Instead of the long list of comparisons. Is there such a thing in Java, or maybe a way to achieve it? I am using a trivial example, my intention is to find out if there is a pattern so I can do these types of tests with enum value lists of many more elements.</p> <p><strong>EDIT:</strong> It looks like EnumSet is the closest thing to what I want. The Naïve way of implementing it is via something like:</p> <pre><code>if (EnumSet.of(ELogLevel.Info, ELogLevel.Debug, ELogLevel.Error).contains(CLog._logLevel)) </code></pre> <p>But under benchmarking, this performs two orders of magnitude slower than the long if/then statement, I guess because the EnumSet is being instantiated every time it runs. This is a problem only for code that runs very often, and even then it's a very minor problem, since over 100M iterations we are talking about 7ms vs 450ms on my box; a very minimal amount of time either way.</p> <p>What I settled on for code that runs very often is to pre-instantiate the EnumSet in a static variable, and use that instance in the loop, which cuts down the runtime back down to a much more palatable 9ms over 100M iterations.</p> <p>So it looks like we have a winner! Thanks guys for your quick replies. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload