Where is the documentation for the values() method of Enum?

rai.skumar picture rai.skumar · Dec 1, 2012 · Viewed 181.4k times · Source

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

Answer

Denys Séguret picture Denys Séguret · Dec 1, 2012

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 class
    (The special implicit values 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.