76

In Java, you can create an enum as follows:

public enum Letter {
    A, B, C, D, E, F, G;

    static {
       for(Letter letter : values()) {
          // do something with letter
       }
    }
}

This question concerns the "values()" method. Specifically, how is it implemented? Usually, I could jump to the source for Java classes using F3 or CTRL+Click in Eclipse (even for classes like String, Character, Integer, and even Enum). It is possible to view the source of the other enum methods (e.g., valueOf(String)).

Does "values()" create a new array each time it is invoked? If I assign it to a local variable and then modify one of the elements, what happens (clearly this won't affect the value returned by values(), which implies that a new array is allocated each time).

Is the code for it native? Or does the JVM / compiler treat it specially, only returning a new instance from values() when it cannot prove that it will not be modified.

3 Answers 3

121

Basically, the compiler (javac) translates your enum into a static array containing all of your values at compile time. When you call values(), it gives you a .clone'd() copy of this array.

Given this simple enum:

public enum Stuff {
   COW, POTATO, MOUSE;
}

You can actually look at the code that Java generates:

public enum Stuff extends Enum<Stuff> {
    /*public static final*/ COW /* = new Stuff("COW", 0) */,
    /*public static final*/ POTATO /* = new Stuff("POTATO", 1) */,
    /*public static final*/ MOUSE /* = new Stuff("MOUSE", 2) */;
    /*synthetic*/ private static final Stuff[] $VALUES = new Stuff[]{Stuff.COW, Stuff.POTATO, Stuff.MOUSE};

    public static Stuff[] values() {
        return (Stuff[])$VALUES.clone();
    }

    public static Stuff valueOf(String name) {
        return (Stuff)Enum.valueOf(Stuff.class, name);
    }

    private Stuff(/*synthetic*/ String $enum$name, /*synthetic*/ int $enum$ordinal) {
        super($enum$name, $enum$ordinal);
    }
}

You can look at how javac 'translates' your classes by making a temporary directory and running:

javac -d <output directory> -XD-printflat filename.java
7
  • 1
    Wouldn't a System.arraycopy be faster?
    – Gandalf
    Commented Aug 3, 2011 at 18:43
  • 3
    Why does values() method clone() the array $VALUES? Why not just return it directly?
    – juung666
    Commented May 18, 2015 at 10:10
  • 5
    @RestInPeace because the array is mutable. See stackoverflow.com/a/16125639/488861 for an example
    – Rytek
    Commented May 28, 2015 at 15:39
  • 3
    I hadn't known about this -XD-printflat. Very useful to understand internal workings of such things. It's a pity that this thing isn't better documented. Thanks for making me aware of this!
    – MvG
    Commented Apr 30, 2016 at 3:49
  • 1
    This helps me understand why I can't constrain a generic method to take enums and then get access to the .values() method. From what you say, it looks like this isn't a method common to all enums, but rather a distinct method that exists in each declared enum and which has nothing in common with the .values() method in any other declared enum.
    – Ryan Lundy
    Commented Apr 20, 2018 at 13:20
2

If you assign it to a local variable the only thing that you can modify is assigning another enum to this variable. This will not change the enum itself because you are only changing the object your variable references.

It seems that the enums are in fact singletons so that only one element from each enum can exist in you whole program this makes the == operator legal for enums.

So there is no performance problem and you can't accidentally change something in your enum definition.

3
  • 2
    i think the OP means modifying the array returned by values(). if this is the same array object that is kept internally (instead of a copy), then modifying it (e.g. assigning one element to another, assigning null to an element, etc.) would mess it up, not only for the enum class, but for any future calls to values()
    – newacct
    Commented Jul 22, 2009 at 5:58
  • 1
    Yes you are right. If there wasn't a clone you could remove a Enum from the array and later calls from values would miss this value.
    – Janusz
    Commented Jul 22, 2009 at 14:43
  • And yet it's just a shallow copy, since the enum instances are unique. Commented Sep 13, 2014 at 2:03
1

Is the code for it native? Or does the JVM / compiler treat it specially, only returning a new instance from values() when it cannot prove that it will not be modified.

1) No. Or at least not in current implementations. See @lucasmo's answer for the evidence.

2) AFAIK, no.

Hypothetically it could do this. However, proving that an array is never modified locally would be complicated and relatively expensive for the JIT to perform. If the array "escapes" from the method that called values(), it gets more complex & more expensive.

The chances are that this (hypothetical) optimization would not pay off ... when averaged over all Java code.

The other issue is that this (hypothetical) optimization might open up security holes.


The interesting thing though is that the JLS does not seem to specify that the values() member returns an array copy. Common sense1 says that it must do ... but it is not actually specified.

1 - It would be a gaping security hole if values() returned a shared (mutable) array of enum values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.