-2

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 ?

  • 1
    It depends on what you want to do but `cachedAnimalsEnumSet` may likely be the best solution. – dan1st Jul 31 '21 at 19:55
  • 2
    Or none of the above. What's wrong with using `Animal.values()`? Of course, it depends on what you need it for. E.g. if you do need a `Set` or a `List`, and you need it often, then yeah, maybe creating a global re-usable one is good. Only you can tell if it needed in your scenario. – Andreas Jul 31 '21 at 20:34

1 Answers1

-2

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.

  • 1
    1) All operations are constant time? What operation wouldn't be if not a set? Contains? Contains always returns true, so why would we need that call? *Meaningless reason.* --- 2) No duplicates? The fact that the set/list is built from `values()` ensures that. *Meaningless reason.* --- 3) Not synchronized? Why would you need that. More importantly would be to make them immutable, since they are globally shared, in which cause synchronization becomes a moot point. – Andreas Jul 31 '21 at 20:40
  • Thank you for the answer! So do you think that the most efficient method is EnumSet? – louiscarpenter3463 Jul 31 '21 at 20:41
  • OP doesn't state their entire use-case, so it is possible that there might be modifications done to the cache. That is why I mentioned that IF multiple threads are involved making it synchronized would be good practice. – PotatoSkull999 Jul 31 '21 at 21:43
  • Also, add/remove operations (which would be called) are also constant time in EnumSet since it is backed by a bit array, and it is also better in terms of memory use, since the backing bit array is of predefined size. – PotatoSkull999 Jul 31 '21 at 21:46