I have a class representing a set of values that will be used as a key in maps.
This class is immutable and I want to make it a singleton for every distinct set of values, using the static factory pattern. The goal is to prevent identical objects from being created many (100+) times and to optimize the equals method.
I am looking for the best way to cache and reuse previous instances of this class. The first thing that pops to mind is a simple hashmap, but are there alternatives?
There are two situations:
enumEnumMapis optimized for itIntegercache instances in a given range forvalueOfMapDepending on the usage pattern, you may choose to only cache, say, the last N instances, instead of all instances created so far. This is the approach used in e.g.
re.compilein Python's regular expression module. If N is small enough (e.g. 5), then a simple array with a linear search may also work just fine.For
Mapbased solution, perhaps a useful implementation isjava.util.LinkedHashMap, which allows you to enforce LRU-like policies if you@OverridetheremoveEldestEntry.There is also
LRUMapfrom Apache Commons Collections that implement this policy more directly.See also
enumsRelated questions
MapMaker, soft keys and values, etc