How to access a specific member in Java enum by Index value?

Viewed 8567

I want to print the 2nd index value i.e SUMMER.

public class Filer
{
    public enum Season { WINTER, SPRING, SUMMER, FALL }

    public static void main(String[] args)
    {
        System.out.println(Season.values(2));//values don't take argument!!
    }
}

How can achieve it?

4 Answers

Your code nearly works. Take a close look at the method signature of Enum#values (documentation).

It is no method that accepts an argument, it returns the whole array. So you need to shift the access after the method as array-access:

Season.values()[2]

You should avoid accessing Enum by index. They depend on their order in the code. If you do some refactoring like "sort project alphabetical":

public enum Season {
    FALL,    // 3 -> 0
    SPRING,  // 1 -> 1
    SUMMER,  // 2 -> 2
    WINTER   // 0 -> 3
}

or later add some values to your enum without remembering your order-depend code, then you will break your code. Instead you may setup a Map<Integer, Season>:

Map<Integer, Season> indexToSeason = new HashMap<>();
indexToSeason.put(0, Season.WINTER);
indexToSeason.put(1, Season.SPRING);
indexToSeason.put(2, Season.SUMMER);
indexToSeason.put(3, Season.FALL);

And then use that map for access:

public Season getSeasonByIndex(int index) {
    return indexToSeason.get(index);
}

If you want to get the enum at a specific index try:

Season.values()[index]

You can access them by typing the value that you want, e.g., Season.WINTER, calling Season.valueOf("WINTER"), or iterating over the .values() result, and pick what you want as @Stultuske stated.

If you search for .values() in Class Enum you may not find it because this method is added by the compiler. Check this answer.

If you need to actually access to the Enum via index value just use Season.values()[someIndex], since .values() return an array T[].

Find more information about Enums here.

System.out.println(Season.values()[2]);

Related