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

后端 未结 2 1801

I need to convert an ordinal int value to an enum value in Java. Which is simple:

MyEnumType value = MyEnumType.values()[ordinal];
2条回答
  •  情深已故
    2020-12-05 18:36

    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 VALUES = Collections.unmodifiableList(Arrays.asList(values()));
      

提交回复
热议问题