Set Value to Enum - Java

27,325

Solution 1

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

Solution 2

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;
    }
}

Solution 3

public enum RPCPacketDataType { 

  PT_UNKNOWN(2), 
  PT_JSON(4),
  PT_BINARY(5); 

  private int type;

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

  public int getNumericType() {
    return type;
  }

  public void setNumericType(int type) {
    this.type = type;
  }

  public static void main(String[] args) {
    RPCPacketDataType.PT_UNKNOWN.setNumericType(0);
    System.out.println("Type: "+RPCPacketDataType.PT_UNKNOWN.getNumericType()); 
    // Type: 0
  }

}

As both #emboss and #Michael said correctly you can use a Contructor which accepts ant int

Share:
27,325
Android-Droid
Author by

Android-Droid

Android developer.

Updated on July 05, 2022

Comments

  • Android-Droid
    Android-Droid almost 2 years

    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.

  • Konstantin Burov
    Konstantin Burov over 12 years
    You may also want to add a getter to have access to the value later.
  • Android-Droid
    Android-Droid over 12 years
    I have another question. How can I do something like that: RPCPacketDataType currentType; if(currentType!=PT_JSON) return;
  • Michael
    Michael over 12 years
    I hope one can easily add any method to this class oneself. The question is about adding values but not retrieving them :)
  • emboss
    emboss over 12 years
    I'd use switch for enums: switch (currentType) { case PT_JSON: ... }
  • Android-Droid
    Android-Droid over 12 years
    Actually I need only to check the PT_JSON,that's why I'm using if statement.But thanks for advance!