How to convert enum value to int?

2020-01-26 16:03发布

I have a function which return a type int. However, I only have a value of the TAX enumeration.

How can I cast the TAX enumeration value to an int?

public enum TAX {
    NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);

    private int value;
    private TAX(int value){
        this.value = value;
    }
}

TAX var = TAX.NOTAX; // This value will differ

public int getTaxValue()
{
  // what do do here?
  // return (int)var;
}

标签: java enums
7条回答
放我归山
2楼-- · 2020-01-26 16:05

A somewhat different approach (at least on Android) is to use the IntDef annotation to combine a set of int constants

@IntDef({NOTAX, SALESTAX, IMPORTEDTAX})
@interface TAX {}
int NOTAX = 0;
int SALESTAX = 10;
int IMPORTEDTAX = 5;

Use as function parameter:

void computeTax(@TAX int taxPercentage){...} 

or in a variable declaration:

@TAX int currentTax = IMPORTEDTAX;
查看更多
等我变得足够好
3楼-- · 2020-01-26 16:06
public enum Tax {

NONE(1), SALES(2), IMPORT(3);

private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public String toString() {
        return Integer.toString(value);
    }
}

class Test {
    System.out.println(Tax.NONE);    //Just an example.
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-26 16:20

Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):

ValueType expected = ValueType.FLOAT;
String value = expected.name();

System.out.println("Name value: " + value);

ValueType actual = ValueType.valueOf(value);

if(expected.equals(actual)) System.out.println("Values are equal");
查看更多
放我归山
5楼-- · 2020-01-26 16:22

If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.

If you want a unique number that represent the enum value, you can use ordinal().

查看更多
孤傲高冷的网名
6楼-- · 2020-01-26 16:25

You'd need to make the enum expose value somehow, e.g.

public enum Tax {
    NONE(0), SALES(10), IMPORT(5);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

...

public int getTaxValue() {
    Tax tax = Tax.NONE; // Or whatever
    return tax.getValue();
}

(I've changed the names to be a bit more conventional and readable, btw.)

This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.

查看更多
Juvenile、少年°
7楼-- · 2020-01-26 16:25

I prefer this:

public enum Color {

   White,

   Green,

   Blue,

   Purple,

   Orange,

   Red
}

then:

//cast enum to int
int color = Color.Blue.ordinal();
查看更多
登录 后发表回答