Load a list of Enums

Asked

Viewed 3,802 times

0

I have a selectOneMenu thus:

<p:selectOneMenu id="diminui" value="#{naturemb.nature.diminui}" effect="clip">
 <f:selectItems itemLabel="#{naturemb.carregarAtributos()}" itemValue="#{naturemb.carregarAtributos()}" />
</p:selectOneMenu>

I want to display on the screen the values of my Enum:

package br.com.pokemax.modelo;

public enum Atributos {

    HP("HP"), ATTACK("Attack"), DEFENSE("Defense"), SPECIAL_ATTACK("Sp. Attack"), SPECIAL_DEFENSE("Sp. Defense"), SPEED(
            "Speed");

    private String nome;

    private Atributos(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

I created a method in Controller like this:

public String carregarAtributos() {
        List<Atributos> lista = Arrays.asList(Atributos.values());
        for (int i = 0; i < lista.size(); i++) {
            return lista.get(i).getNome();
        }

        return "";
    }

But it’s not working, someone can help me ?

  • Here’s a hint. Use theEnhanced-for: for (Atributos a : Atributos.values()) { return lista.getNome(); }

  • @Victorstafusa what the difference and advantage?

  • Douglas, with that you don’t need to be wearing one int all the time to index and find the element, thus making the code much simpler. In addition, for some list types (linked lists), the method get(int) is relatively slow, but with this form of iteration, you avoid it.

3 answers

2

If you already have an Enum, you can use it without creating a String list. It’s better because it makes reuse easier. In your example, just do:

public List<Atributos> carregarAtributos() {
   return Arrays.asList(Atributos.values());
}

And in selectOneMenu:

<p:selectOneMenu id="diminui" value="#{naturemb.nature.diminui}" effect="clip">
   <f:selectItems var="atributo" itemLabel="#{atributo.nome}" itemValue="#{atributo}" value="#{naturemb.carregarAtributos()}"/>
</p:selectOneMenu>

Note. 1: how you will use the Enum instead of the string, you have to change the type to Enum tb in the target variable.

Note. 2: I think it is not necessary to put a setNome in Num because you will not be able to change the value at runtime, only in creation (in Atributos(String nome)).

1

Douglas,

The easiest way to return the list of enums is:

public EnumSet<Atributos> listarAtributos() {
    return EnumSet.allOf(Atributos.class);
}

I hope it helps ;)

Hug!

1


Change your method to:

public List<String> carregarAtributos() {
        List<Atributos> lista = Arrays.asList(Atributos.values());
        List<String> retorno = new List<String>();
        for (int i = 0; i < lista.size(); i++) {
           retorno.add(lista.get(i).getNome());
        }
        return retorno;
}

Browser other questions tagged

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