I have to develop something like a game of life. For that, I have a class called CellPosition that has x and y fields. In order to efficiently use memory, I would like to use some kind of factory method.
CellPosition.at(int x, int y) which would return an instance of CellPosition. I would like though to cache the objects that have the same x, y pair. I though of a List or a HashMap, but I cannot figure out what to use as a key. A concatenation of x and y in a string is doubtingly a good idea.
On the other hand, is it a good idea to just create an object each time and just redefine the equals() method to compare the objects and throw away any caching?
If you don’t mind using Guava, just:
CellPositioninstances immutable, thenInterner<CellPosition>(obtained fromInterners), thenSomething like this:
You could also use a Guava
Cacheinstead of anInterner, but there’s not much point since you’d have to construct an int-pair key for the cache — which you’re doing anyway for the interner, in fewer LoC.