switch not recognizing ENUM as constant [duplicate]

-1
public enum enumUpdateAction {
    NEW(0), CHANGE(1), DELETE(2), DELETE_THRU(3), DELETE_FROM(4);

    public int codigo;

    enumUpdateAction(int codigo) {
        this.codigo = codigo;
    }

    public int getCodigo() {
        return this.codigo;
    }
}

...

switch (Eventos.get(0).getUpdateaction()) {

            case enumUpdateAction.NEW.getCodigo(): 
                ArrayEventos.add(InserirOrdenado(ArrayEventos, Ordem), Ordem);
                break;
}

After creating the enum, I'm trying to use this value inside a switch (in this case, NEW corresponds to 0 and therefore I'm trying to use 0 inside the case), but I get the error "constant expression required". Can anyone tell me why this happens?

    
asked by anonymous 24.02.2017 / 18:54

2 answers

2

It happens because you are trying to compare the enum code with the enum itself, because getUpdateaction() returns the enum itself, but you try to make the case with the enum code, thus causing that error, enough you drop enumUpdateAction.NEW.getCodigo() and put enumUpdateAction.NEW .

    
24.02.2017 / 19:08
1

A value used in a case must be a constant variable , that is, a variable final primitive type or String initialized at compile time, or a enum . This is not the case for the value returned by the getCodigo method of its enum .

If the method getUpdateAction returns a enum just do this:

Use the name of enum in case :

switch(Eventos.get(0).getUpdateaction()) {
    case NEW:
        ArrayEventos.add(InserirOrdenado(ArrayEventos, Ordem), Ordem);
        break;

}

If he returns the code of his enum , change his enum to:

public enum EnumUpdateAction {
    NEW(0), CHANGE(1), DELETE(2), DELETE_THRU(3), DELETE_FROM(4);


    private static final EnumUpdateAction VALUES[] = EnumUpdateAction.values();

    private final int codigo;

    private EnumUpdateAction(int codigo) {
        this.codigo = codigo;
    }

    public int getCodigo() {
        return this.codigo;
    }


    public static final EnumUpdateAction deCodigo(int codigo) {
        for(EnumUpdateAction e : VALUES) {
            if(e.codigo == codigo) {
                return e;
            }
        }
        throw new IllegalArgumentException("codigo inválido: " + codigo);
    }
}

And its switch to:

switch(EnumUpdateAction.deCodigo(Eventos.get(0).getUpdateaction())) {
    case NEW:
        ArrayEventos.add(InserirOrdenado(ArrayEventos, Ordem), Ordem);
        break;

}

Note: By convention , the class names in Java are written in CamelCase .

    
24.02.2017 / 19:13