Learning to use ENUM in Java

Asked

Viewed 1,828 times

1

Good afternoon.

I’m learning to use the guys enum in Java and facing some problems.

First of all, I created my own enum as follows:

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;
    }
}

Now, I need to use such an Enum inside a Switch, in another class:

public static LinkedList<LinkedList<Eventos>> Working(enum_type tipo, enum_updateAction updateAction) {

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

        case enum_updateAction.NEW://enum_updateAction.NEW: // 0 = new
                ArrayEventos.add(InserirOrdenado(ArrayEventos, Ordem), Ordem);
                break;

    }


}

The Eventos.get(0).getUpdateaction() returns a int. I could use in cases numbers from 0 to 2, but how do I know that each number represents BID, OFFER or TRADE, I’m trying to use these words directly on switch, with the aid of enum. Meanwhile, I get that "enum_updateAction.NEW cannot be converted to int". Can anyone tell me how I get the number value of NEW of enum, and not the word NEW in itself?

2 answers

3


All enum has a method called ordinal() which gives the position in which it was declared within the class, the first element being that of ordinal() == 0. Why, that’s exactly what your field codigo makes. So, you don’t need to use this field to reinvent the wheel, just use the ordinal().

public enum EnumUpdateAction {
    NEW, CHANGE, DELETE, DELETE_THRU, DELETE_FROM;
}

Moreover, all enum has a method values() which returns an array of the same type as enum containing the elements of that enum in the order in which they are defined. You can use this to translate the values of ordinal() for the elements.

In the switch, you can use the elements of enums directly, referencing them by their respective names. Do not need any code int for that reason:

public static List<? extends List<Eventos>> working(EnumType tipo, EnumUpdateAction updateAction) {

    switch (EnumUpdateAction.values()[eventos.get(0).getUpdateAction()]) {
        case NEW:
            ArrayEventos.add(inserirOrdenado(arrayEventos, ordem), ordem);
            break;
        case CHANGE:
            // ...
            break;
        case DELETE:
            // ...
            break;
    }
}

I also notice that if eventos.get(0) return EnumUpdateAction instead of int, your switch would be simpler:

switch (eventos.get(0)) {

Also, please obey the language conventions.

And I notice that maybe in your code, what you really wanted was a switch (updateAction) { ... }.

See in ideone an example with enum in switch:

class EnumComSwitch {
    private static enum MeuEnum {
        NEW, CHANGE, DELETE, BLABLA;
    }

    public static void main(String[] args) {
        MeuEnum elemento = MeuEnum.CHANGE;
        switch (elemento) {
            case NEW:
                System.out.println("Este é o NEW");
                break;
            case CHANGE:
                System.out.println("Este é o CHANGE");
                break;
            case DELETE:
                System.out.println("Este é o DELETE");
                break;
            case BLABLA:
                System.out.println("Este é o BLABLA");
                break;
        }
    }
}
  • The switch(eventos.get(0)) is not an option. This Eventos.get(0).getUpdateaction returns an int that I read from a file, being 0 to 4. Depending on what it returns, I take an action (hence the switch). However, when I use NEW directly in the case, a huge list of options for import is presented. I tried to instantiate the ENUM to solve, however the compiler even reported that it is already instantiated. I’m looking for alternatives, but thank you very much for the information. About the language conventions, I’m going back to studying java for now, I’m a little lost yet

  • @Marcosvinicius No import needed, just import the class enum (that you must already be importing) and nothing more. Skip the list of import suggestions. - When this list appears, press ESC. Also, one of the basic premises of enum is to be a fixed and immutable set of objects, and therefore should not be instantiable, as this would cause them to cease to be a fixed and immutable set.

  • @Marcosvinicius I added an example. See it working here: http://ideone.com/TM8jAM

  • Beauty man. Thank you so much for your effort and patience. Now I understand how to work with this enum.

1

First I’ll use another name for enum, considering the convection of code, which classes should start with capital letters and _ should be avoided.

There are several ways to make the comparison you want, one of them is to transform the int that represents noo enum (consisderando que you can put any code in any order) desired.

public enum Type {
  BID(0), OFFER(1), TRADE(2);

  public final int codigo;

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

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

  public static Type getType(int codigo) {
    for(Type type : Type.values()) {
      if (type.getCodigo() == codigo) {
        return type;
      }
    }

    return null;
  }
}

So your comparison would be as follows:

public static LinkedList<LinkedList<Eventos>> working() {
  Type type = Type.getType(Eventos.get(0).getUpdateaction());

  switch(type) {
      case Type.NEW:
        arrayEventos.add(InserirOrdenado(arrayEventos, ordem), ordem);
        break;
  }
}

Note that I used the method Type#get to transform the int of Eventos.get(0).getUpdateaction() to obtain the enum concerning him.


The second way would be, using the implementation of enum previous, check as follows:

public static LinkedList<LinkedList<Eventos>> working() {
  switch(Eventos.get(0).getUpdateaction()) {
      case Type.NEW.getCodigo():
        ArrayEventos.add(InserirOrdenado(arrayEventos, ordem), ordem);
        break;
  }
}

If you guarantee that the order will actually refer to int that will use there is a solution in this answer.


Reference:

Answer to a similar question in Stackoverflow: How to Retrieve Enum name using the id?

  • @Marcosvinicius just takes a look at the remark I put

  • All right. I’ve got those questions. When using case enumUpdateAction.NEW.getCodigo(): , the "Constant Expression required" error is shown, and this Enum is an already defined constant. You know why it can happen?

  • The enumUpdateAction is a variable? If it is you should do so: enum_type.NEW.getCodigo()

  • In this case, enumUpdateAction is another ENUM, practically identical to enumType. I should have posted the enumUpdateAction, nor realized that I posted the wrong one. The enumUpdateAction has NEW(0), CHANGE(1), DELETE(2), DELETE_THRU(3), DELETE_FROM(4);. I’m trying to get the character 0, referring to the new, when I use enum_type.NEW.getCodigo(), but I can’t. Such a constant error Expression required appears. Can I be clear? Haha

  • @Marcosvinicius tries the second way I put it there

  • 1

    Man, I hate voting negative, especially on a nice guy like you that I like a lot. But what you created was a very big complication that ends up more disorienting and confusing than helping. Just use the methods ordinal() and values(). Also, you can use the enum directly on switch, you don’t have to kill yourself to extract ints.

  • @Victorstafusa Thanks for the feedback, but the second part of what you mentioned is in the second part of the reply. I don’t see the first part as wrong, but that’s okay, especially considering that he could, for example, use a code that wasn’t sequential and all...

  • @Marcosvinicius to work the attribute in the case codigo in the enum must be declared as final. Take a look at the answer now

  • 1

    Oops. Problem solved man. Thank you so much for the help and excuse the ignorance. Haha

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.