Search code examples
javacachingenumsenumset

Caching enum values


I have more enums with some values and I want asked you what the method is good to cache enum values:

For example:

public enum Animal {
Dog, Cat, Cow;

static Animal[] values;
static EnumSet<Animal> cachedAnimalsEnumSet;
static List<Animal> cachedAnimalsList;

static {
    values = values();
    cachedAnimalsEnumSet = EnumSet.allOf(Animal.class);
    cachedAnimalsList = Arrays.asList(Animal.values());
    }
}

Which is the best way: values, cachedAnimalsEnumSet or cachedAnimalsList ?


Solution

  • Assuming that your purpose of caching is to avoid creation of new array every time anyone calls Animal.values(), and instead just use the cached value. I'd recommend using EnumSet for following reasons:

    1. All basic operations are constant time.
    2. There is not point in caching duplicate enum values, and the Set implementation takes care of it for you.

    However, couple things to consider are that null values are not allowed in EnumSet (highly doubt you want to cache nulls). And second thing to be careful about is that EnumSet is not synchronized. So if you are going to have multiple threads access, and modify this cache, you'd have to wrap it using Collections.synchronizedSet method.