It's possible to have an enum with byte values instead of int values in Java ?
public enum PacketTypes {
REQUEST_CO_SERVER, ACCEPTANCE, REFUSAL, REQUEST_CO_USER, PUBLIC_MSG, PRIVATE_MSG
}
It's possible to have an enum with byte values instead of int values in Java ?
public enum PacketTypes {
REQUEST_CO_SERVER, ACCEPTANCE, REFUSAL, REQUEST_CO_USER, PUBLIC_MSG, PRIVATE_MSG
}
The Java Enum is a type-safe implementation where you actually don't care what type your constants map to. Strictly speaking, the answer to your question is "no" since the java.lang.Enum.ordinal
is baked as int
.
If you are looking for some implementation of bit flags, you might want java.util.BitSet.
As commented by @user15244370, if you want to associate a value with each enum object, such as a byte value, declare a member field on the enum. Add a constructor that takes the desired value for each enum object to be stored on the member field.
As mentioned in the Comment by user15244370 and in the correct Answer by Tomáš Záluský, here is example code of an enum carrying a byte
member field initialized with value passed to an enum constructor.
By the way, the name of your enum should be singular rather than plural, PacketType
rather than PacketTypes
.
enum PacketType {
ACCEPTANCE ( (byte) 101 ), // Calling constructor on this enum class.
REFUSAL ( (byte) 42 ) ;
// Member field.
private byte byteCode ;
// Constructor.
PacketType ( byte b ) { this.byteCode = b ; }
// Getter method, for a read-only property of this enum.
byte getByteCode() { return this.byteCode ; }
}
Here I am using casting of an int
to get a byte
. Apparently Java does not offer syntax for a byte
literal. See How do you specify a byte literal in Java?.
Now see that enum in use with the following code running live at IdeOne.com.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(
PacketType.REFUSAL.toString()
+ " = "
+ PacketType.REFUSAL.getByteCode()
) ;
}
}
enum PacketType {
ACCEPTANCE ( (byte) 101 ), // Calling constructor on this enum class.
REFUSAL ( (byte) 42 ) ;
private byte byteCode ; // Member field.
PacketType ( byte b ) { this.byteCode = b ; } // Constructor.
byte getByteCode() { return this.byteCode ; } // Getter method, for a read-only property of this enum.
}
REFUSAL = 42