Switch housing with "static final byte"

I need to use switch case with byte contants. I have static final constants declared as follows:

 private static final byte[] X_CONST = {2}; private static final byte[] Y_CONST = {3}; 

Then I want to use the switch case as shown below:

 byte[] x={3}; switch (x[0]){ case X_CONST[0]: ...; break; case Y_CONST[0]: ...; break; } 
+4
source share
4 answers

An array may be static final, but the contents of the array are not. Thus, this is not allowed because the value of the key argument, since the value itself can be changed at run time. Instead, you need to specify private static final byte X_CONST = 2 .

+7
source

You declared constants as arrays of bytes. Switch statements cannot be used with array types.

Try the following ad:

 private static final byte X_CONST = 2; private static final byte Y_CONST = 3; 
+3
source

Other answers indicate a problem in your code. As a workaround, you can create an enumeration to use the switch statement, for example:

 public enum MY_ENUM { X_CONST((byte)2), Y_CONST((byte)3); private final byte value; private MY_ENUM(byte value) { this.value = value; } public byte getValue() { return value; } public static MY_ENUM valueOf(byte b) { MY_ENUM[] values = MY_ENUM.values(); for (int i = 0; i < values.length; i++) { if (values[i].getValue() == b) { return values[i]; } } throw new IllegalArgumentException("Invalid input byte"); } } 

...

 public static void main(String[] args) { byte[] x={3}; switch (MY_ENUM.valueOf(x[0])) { case X_CONST: ...; break; case Y_CONST: ...; break; } } 
+1
source

The switch statement cannot be used with an array.

The switch works with byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and several special classes that wrap some primitive types: character, Byte, Short, and Integer.

0
source

All Articles