Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if a value is one of many constants

Tags:

java

In Python, you can:

if error_code in (1213,1205,1317,2006,2013):
    ...

How can you concisely do the same kind of check - seeing if an int is one of many choices - in Java?

UPDATE: the solution I adopted:

private static final Set<Integer> MySQLRetryCodes = 
    Collections.unmodifiableSet(new HashSet<Integer>(
         Arrays.asList(
            1205, // lock timeout
            1213, // deadlock
            1317,2006,2013 // variations on losing connection to server
         )));

and then later:

if(MySQLRetryCodes.contains(sqlError.getErrorCode()) {
    ...
like image 216
Will Avatar asked Nov 15 '25 11:11

Will


2 Answers

The constants would be in a list and you would use the contains() method as follows:

if (Arrays.asList(1213,1205,1317,2006,2013).contains(error_code)) {
    ...
}

The best way is to declare this list as a constant somewhere and use it, as follows:

public static final List<Integer> ERROR_CODES = 
    Arrays.asList(1213,1205,1317,2006,2013);

...
if (ERROR_CODES.contains(error_code)) {
    ...
}
like image 76
Vikdor Avatar answered Nov 18 '25 05:11

Vikdor


I would use HashSet :

  if (new HashSet<Integer>
          (Arrays.asList(1213,1205,1317,2006,2013)).contains(error_code)){

       //do something

   }
like image 35
Grisha Weintraub Avatar answered Nov 18 '25 04:11

Grisha Weintraub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!