Use of enum in the cases of a switch

0

Hello, good afternoon.

I have a problem with using ENUM to replace a number in the case. In order to make my code more intuitive and do not use numbers in switch cases, I intend to use an ENUM in their place. Example:

private static enum EnumFrutas {
    MACA(0), ABACATE(1), PERA(2);

    public final int codigo;

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

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

public static LinkedList<LinkedList<Eventos>> Working() {
    switch (Eventos.get(0).getFruta()) {
        case 0: 
            tomaAcaoParaMaçã;
            break;
        case 2: 
            tomaAcaoParaAbacate;
            break;
    }
}

Knowing that Eventos.get(0).getFruta() returns an INT, I want to use the value which MACA matches in ENUM (in this case, 0) within the case:

case MACA: 
        tomaAcaoParaMaçã;
        break;

How can I do this, since typing the word MACA itself does not work?

    
asked by anonymous 03.03.2017 / 18:31

2 answers

2

You've tried:

switch (EnumFrutas.values()[Eventos.get(0).getFruta()]) {
      case MACA: 
          tomaAcaoParaMaçã;
          break;
      case ABACATE: 
          tomaAcaoParaAbacate;
          break;
}

So if getFruta is 0 it goes behind the enum part where the value is 0 in the case MACA

    
03.03.2017 / 18:56
0

I'll run the risk of being negatively evading a little of your question, but suggesting a better solution to your problem.

How about forcing in the Enum the declaration of an action for each fruit?

public interface Action {
   void executa();
}

private static enum EnumFrutas {
    MACA(0, new MacaAction()), 
    ABACATE(1, new AbacateAction()), 
    PERA(2, new PeraAction());

    private int codigo;

    private Action action;

    EnumFrutas(int codigo, Action action) {
        this.codigo = codigo;
        this.action = action;
    }

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

    public Action getAction() {
        return this.action;
    }
}

To perform the action, you can remove the problematic switch by doing just:

public static LinkedList<LinkedList<Eventos>> Working() {
   EnumFruta fruta = Eventos.get(0).getEnumFruta();
    fruta.getAction().executa();
}
    
03.03.2017 / 19:15