How to go through Enum in Java

Asked

Viewed 3,265 times

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 make a comparison of values. How can I go through each Enum value and compare with a string x ?

  • @Renan I will have an x method that will receive a text as parameter... Inside this text I will check if any of the values of Enum is between the text, understood ?

2 answers

6


To get all the values that exist on Enum, do the following:

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

ou

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

With the already populated list, you just need to browse and compare

ex:

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

I hope I’ve helped.

  • Show, thank you very much.

2

I have an example that can 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... iterates enter the array to get the value of my Enum. Note: to interact with Enum is Enum.values() (the values is an array of Enum).

  • 3

    And how would that solve the question problem? I reread the answer and could not even relate as a solution.

Browser other questions tagged

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