How to go through Enum in Java

2

I have the following Enum:

public enum TipoPokemon {

    FIRE("FIRE"),
    WATER("WATER"),
    GRASS("GRASS"),
    ELECTRIC("ELECTRIC"),
    ICE("ICE"),
    DARK("DARK"),
    GHOST("GHOST"),
    FAIRY("FAIRY"),
    PSYCHIC("PSYCHIC"),
    DRAGON("DRAGON"),
    POISON("POISON"),
    GROUND("GROUND"),
    ROCK("ROCK"),
    NORMAL("NORMAL"),
    BUG("BUG"),
    FIGHTING("FIGHTING"),
    STEEL("STEEL"),
    FLYING("FLYING");

    private String nome;

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

    public String getNome() {
        return nome;
    }

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

}

I need to go through each of these values in another class to do a comparison of values. How can I go through each Enum value and compare with a string x?

    
asked by anonymous 10.11.2016 / 16:26

2 answers

6

To get all the values that exist in the enum, do the following:

List<TipoPokemon> list = Arrays.asList(TipoPokemon.values());

ou

List<TipoPokemon> list = new ArrayList<TipoPokemon>(EnumSet.allOf(TipoPokemon.class));

With the list already populated, you just have to go through and compare

ex:

for (int i = 0; i < list.size(); i++){
    boolean exemplo = list.get(i).name() == "X";
}

I hope I have helped.

    
10.11.2016 / 16:44
2

I have an example that might help you:

public enum AlgarismoRomano {

    I(1), V(5), X(10), L(50), C(100), D(500), M(1000);

    private int numeroArabico;

    private AlgarismoRomano(int numeroArabico) {
        this.numeroArabico = numeroArabico;
    }

    public static int retornarNumeroArabico(char numeroRomano) {
        return valueOf(String.valueOf(numeroRomano)).numeroArabico;
    }

    public static List<Character> getAlgarismosRomanos() {
        List<Character> algarismos = new ArrayList<Character>();

        for (AlgarismoRomano algarismo : values())
            algarismos.add(algarismo.toString().toCharArray()[0]);

        return algarismos;
    }

}

The method getAlgarismosRomanos does this ... itera enters the array to get the value of my enum. Note: to interact in the enum is Enum.values() (the values is an Enum array).

    
10.11.2016 / 16:40