0

From reading the Enum Types, The Java Tutorials:

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

I'd like to know what exactly the values() method does. Is it effectively just returning a class member / constant, or is it more going on under the hood? The following code is in no way meant to demonstrate best practise but highlights how the answer this question would affect how I might approach a problem:

If values() returns a class member / constant I would consider calling it liberally (see getAllValues()), like this:

enum ExampleEnum {
    A("A's String"), B("B's String"), C("C's String");
    ExampleEnum(String someValue) {
        this.someValue = someValue;
    }

    private final String someValue;

    private String[] getAllValues() {
        String[] result = new String[values().length];
        for (int i = 0; i < values().length; i++) {
            result[i] = values()[i].someValue;
        }
        return result;
    }
}

If however it was doing actual work, I'd change getAllValues() as follows:

private String[] getAllValues() {
    ExampleEnum[] values = values();
    String[] result = new String[values.length];
    for (int i = 0; i < values.length; i++) {
        result[i] = values[i].someValue;
    }
    return result;
}
Robert Bain
  • 9,113
  • 8
  • 44
  • 63

1 Answers1

4

Each time you call values() you are creating new array filled with enum constants. You can easy test it with == operator

System.out.println(ExampleEnum.values()==ExampleEnum.values());//prints false

So second option would be better because it creates this array once. But to improve it you could simply store result of values() outside of this method and reuse it when need. This way you would simply invoke it once. You can also create collection of someValue elements earlier, store it as unmodifiable collection (like List) and return it.

So your code could look like:

enum ExampleEnum {
    A("A's String"), B("B's String"), C("C's String");
    ExampleEnum(String someValue) {
        this.someValue = someValue;
    }

    private final String someValue;

    private static final ExampleEnum[] vals = values();
    private static final List<String> names = Collections.unmodifiableList(
            Stream.of(vals).map(en -> en.someValue).collect(Collectors.toList()));

    public static List<String> getAllValues() {
        return names;
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269