I declare an enum as :
enum Sex {MALE,FEMALE};
And then, iterate enum as shown below :
for(Sex v : Sex.values()){ System.out.println(" values :"+ v); }
I checked the Java API but can't find the values() method? I'm curious as to where this method comes from?
API link : https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html
values() method can be used to return all values present inside the enum. Order is important in enums.By using the ordinal() method, each enum constant index can be found, just like an array index. valueOf() method returns the enum constant of the specified string value if exists.
The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.
A standard enum is usually implemented as an int32, the compiler will handle your enum as a synonym of int32 . Once a list of values is created for a enumeration those values are stored as literals against their display name(access name given at the time of declaration of enum).
You can't see this method in javadoc because it's added by the compiler.
Documented in three places :
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.
Enum.valueOf
classvalues
method is mentioned in description of valueOf
method)All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.
The values
function simply list all values of the enumeration.
The method is implicitly defined (i.e. generated by the compiler).
From the JLS:
In addition, if
E
is the name of anenum
type, then that type has the following implicitly declaredstatic
methods:/** * Returns an array containing the constants of this enum * type, in the order they're declared. This method may be * used to iterate over the constants as follows: * * for(E c : E.values()) * System.out.println(c); * * @return an array containing the constants of this enum * type, in the order they're declared */ public static E[] values(); /** * Returns the enum constant of this type with the specified * name. * The string must match exactly an identifier used to declare * an enum constant in this type. (Extraneous whitespace * characters are not permitted.) * * @return the enum constant with the specified name * @throws IllegalArgumentException if this enum type has no * constant with the specified name */ public static E valueOf(String name);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With