Does the Enum#values() allocate memory on each call?

Yes.

Java doesn’t have mechanism which lets us create unmodifiable array. So if values() would return same mutable array, we risk that someone could change its content for everyone.

So until unmodifiable arrays will be introduced to Java, for safety values() must return new/separate array holding all values.

We can test it with == operator:

MyEnumType[] arr1 = MyEnumType.values();
MyEnumType[] arr2 = MyEnumType.values();
System.out.println(arr1 == arr2);       //false

If you want to avoid recreating this array you can simply store it and reuse result of values() later. There are few ways to do it, like.

  • you can create private array and allow access to its content only via getter method like

    private static final MyEnumType[] VALUES = values();// to avoid recreating array
    
    MyEnumType getByOrdinal(int){
        return VALUES[int];
    }
    
  • you can store result of values() in unmodifiable collection like List to ensure that its content will not be changed (now such list can be public).

    public static final List<MyEnumType> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
    

Leave a Comment