4

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?

1stthomas
  • 731
  • 2
  • 15
  • 22
Suvam Roy
  • 963
  • 1
  • 8
  • 19

4 Answers4

9

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);
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • That was really informative. But as you declared Map indexToSeason = new HashMap<>(); shouldn't it be like indexToSeason.put(0,Season.WINTER); and so on? – Suvam Roy Nov 24 '17 at 14:42
  • @Zabuza You should probably use `new HashMap<>(6)` because default initial capacity is 16 and you don't need that much. Default load factor is 0.75 so 6 is optimal for 4 items. – TheKarlo95 Nov 24 '17 at 14:59
  • @TheKarlo95 Good point but I doubt that such micro-optimization will help here that much. In the worst case it only confuses a reader. Another alternative would be to use the very optimized factory methods `Map.of(...)` from **Java 9**. – Zabuzard Nov 24 '17 at 18:11
6

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

Season.values()[index]
Matt Clegg
  • 359
  • 1
  • 4
  • 17
4

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.

LuisFerrolho
  • 417
  • 3
  • 13
2

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

Sameera
  • 85
  • 5