Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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

1 Answer

0 votes
by (46k points)

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.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 4, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 30, 2019 in Java by Krishna (2.6k points)

Browse Categories

...