Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Value to Enum - Java

I'm trying to set values to enum in my java application....but I can't do that.

Am I doing it wrong???

public enum RPCPacketDataType {
    PT_UNKNOWN(2),
    PT_JSON(4),
    PT_BINARY(5)
};

It's giving me this error : The constructor RPCPacket.RPCPacketDataType(int) is undefined.

like image 434
Android-Droid Avatar asked Aug 25 '11 13:08

Android-Droid


People also ask

Can we set values to enum in Java?

You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s). The initialization should be done only once. Therefore, the constructor must be declared private or default. To returns the values of the constants using an instance method(getter).

Can we set values in enum?

Overview. The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.

Can we initialize enum in Java?

Like Java Classes, Enums can contain Constructors, Member Variables, Methods and also implement Interfaces. However, the only difference is that Enum constants are public, static, and final. Besides, you can instantiate it using the 'new' keyword or extend any other class explicitly.


2 Answers

public enum RPCPacketDataType
{
    PT_UNKNOWN(2),
    PT_JSON(4),
    PT_BINARY(5);

    RPCPacketDataType (int i)
    {
        this.type = i;
    }

    private int type;

    public int getNumericType()
    {
        return type;
    }
}

You can also define methods on your enum as you would in a "normal" class.

 System.out.println(RPCPacketDataType.PT_JSON.getNumericType() // => 4
like image 129
emboss Avatar answered Sep 17 '22 23:09

emboss


You should create a Contructor which accepts an int parameter. Also add an int field which will hold the passed value.

public enum RPCPacketDataType {
    PT_UNKNOWN(2),
    PT_JSON(4),
    PT_BINARY(5);

    private int mValue;

    RPCPacketDataType(int value) {
        mValue = value;
    }
}
like image 32
Michael Avatar answered Sep 20 '22 23:09

Michael