Enum#values() 是否在每次调用时分配内存? [英] Does the Enum#values() allocate memory on each call?

查看:32
本文介绍了Enum#values() 是否在每次调用时分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Java 中将序数 int 值转换为枚举值.这很简单:

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

MyEnumType value = MyEnumType.values()[ordinal];

values() 方法是隐式的,我找不到它的源代码,因此问题.

The values() method is implicit, and I cannot locate the source code for it, hence the question.

MyEnumType.values() 是否分配了一个新数组?如果是这样,我应该在第一次调用时缓存数组吗?假设转换会经常被调用.

Does the MyEnumType.values() allocate a new array or not? And if it does, should I cache the array when first called? Suppose that the conversion will be called quite often.

推荐答案

是.

Java 没有让我们创建不可修改数组的机制.因此,如果 values() 返回相同的可变数组,我们就有可能为每个人更改其内容.

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.

因此,在 Java 引入不可修改的数组之前,为了安全,values() 必须返回包含所有值的新/单独数组.

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

<小时>

如果你想避免重新创建这个数组,你可以简单地存储它并在以后重用 values() 的结果.有几种方法可以做到,例如.


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];
}

  • 您可以将 values() 的结果存储在不可修改的集合中,例如 List 以确保其内容不会被更改(现在此类列表可以公开).

  • 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()));
    

  • 这篇关于Enum#values() 是否在每次调用时分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆