0

I am a bit curious about how values() method works in Enum type in Java. As seen in Java Specification Document, we can iterate over all values of a certain enum type in a for each loop. e.g.

for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
                  p, p.surfaceWeight(mass));
}

I think for each loop iterate over all values. In this call we are calling a method repeatedly in each loop call so how will it iterate over all enum type or values() method employ iterator of some sort. Can anybody help me with the documentation of implementation of this method?

Neelam
  • 360
  • 4
  • 14
  • What is your question? – Andremoniy May 07 '15 at 07:22
  • 2
    *"In this call we are calling a method repeatedly in each loop call"* No, the `values()` method will be called _once_ and then iterated over the returned Array. – Tom May 07 '15 at 07:26
  • Have a look at this SO answer which describes in detail [how-is-javas-for-loop-code-generated-by-the-compiler](https://stackoverflow.com/questions/3433282/how-is-javas-for-loop-code-generated-by-the-compiler#3433775) – SubOptimal May 07 '15 at 07:29
  • 1
    @Tom `values()` returns an array. There is no `Iterable` involded in this case. From the javadoc `Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:` – SubOptimal May 07 '15 at 07:30
  • @SubOptimal Yes, you're right (edited that comment). The enhanced for loop can handle both :). – Tom May 07 '15 at 07:31

3 Answers3

5

The values() method returns an array of enum values. In Java you can iterate over array using for(Object obj : arr) syntax. It's just a syntactic sugar. During the compilation the implicit int local variable will be created and the cycle will be rewritten like this:

Planet[] vals = Planet.values();
for(int i=0; i<vals.length; i++) {
    Planet p = vals[i];
    System.out.printf("Your weight on %s is %f%n",
              p, p.surfaceWeight(mass));
}
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • This might be interesting: [JLS about the enhanced for loop](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2). – Tom May 07 '15 at 07:32
0

You are right - .values() returns an array of the possible values of the enum.

This array can be used to iterate over, and in each iteration step, you get another value of this Enum which you can use like any other of them - e. g., call methods on them.

glglgl
  • 89,107
  • 13
  • 149
  • 217
0

The method values() is generated at compile time.

Every enum is a subclass of java.lang.Enum. Internally, it keeps your enum elements in an array.

When values() is called, a new array is generated and copied before returning it to you.

dejvuth
  • 6,986
  • 3
  • 33
  • 36