Handy
Handy

Reputation: 13

Enums with constructors and using it in switch JAVA

I have enum, for example:

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

    private final int value;

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

    public int getValue() {
        return value;
    }
}

And I want to use it enum in switch:

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

but IDE says "Constant expression required". How can I use Enum this type in switch?

Upvotes: 1

Views: 823

Answers (3)

WonderCsabo
WonderCsabo

Reputation: 12207

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

Upvotes: 2

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

Upvotes: 0

khelwood
khelwood

Reputation: 59212

You can use an enum in a switch, but your cases must be the items of the enum themselves, not a method return value.

Type x = ...

switch (x) {
    case Type1: ...
       break;
    case Type2: ...
       break;
    case Type3: ...
       break;
}

Upvotes: 1

Related Questions