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

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

问题描述

我需要将序号 int 转换为Java中的枚举值。这很简单:

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.

推荐答案

是, MyEnumType.values() code>创建每个填充枚举元素的新数组。您可以使用 == 运算符进行测试。

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

Java没有机制可以让我们创建不可修改的数组。因此,如果 values()将始终返回相同的数组实例,那么我们有可能会为每个人改变其内容。

所以直到不可修改的数组机制将引入Java,以避免数组可变性问题 values()方法必须创建并返回原始数组的副本。

Java doesn't have mechanism which lets us create unmodifiable array. So if values() would always return same instance of array, we would risk that someone could change its content for everyone.
So until unmodifiable array mechanism will be introduced to Java, to avoid arrays mutability problem values() method must create and return copy of original array.

如果你想避免重新创建这个数组,你可以简单地存储它,并且稍后重用 values()的后续结果。几乎没有办法做到这一点。

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


  • 您可以创建私人数组,只允许通过getter方法访问其内容,如

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


  • 您还可以存储值的结果()在不可修改的集合中,如 List ,以确保其内容不会更改(现在此列表可以公开)。

  • you can also 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<X> values = Collections.unmodifiableList(Arrays.asList(values()));
    


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

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