簡體   English   中英

帶有構造函數的枚舉,並在開關JAVA中使用它

[英]Enums with constructors and using it in switch JAVA

我有枚舉,例如:

public enum Type {
    Type1(10),
    Type2(25),
    Type3(110);

    private final int value;

    Type(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

我想在開關中使用它的枚舉:

switch (indexSector) {
    case Type.Type2.getValue():
    //...
    break;
}

但是IDE會說“需要常量表達式”。 如何在交換機中使用Enum這種類型?

Type indexSector = ...;
int value = indexSector.getValue();
switch (indexSector) {
    case Type2:
        // you can use the int from the value variable
        //...
    break;
}

您可以在開關中使用枚舉,但是您的案例必須是枚舉本身的項目,而不是方法的返回值。

Type x = ...

switch (x) {
    case Type1: ...
       break;
    case Type2: ...
       break;
    case Type3: ...
       break;
}
Type indexType = ...
switch (indexType) {
    case Type.Type1:
    //...
    break;
    case Type.Type2:
        int indexValue = indexType.getValue();
    //...
    break;
    case Type.Type3:
    //...
    break;
    default:
    break;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM