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;
}