I have an enum
let's say with four values. Let's call them A, B, C, D.
public enum Categories
{
A,
B,
C,
D
}
I then have a Thing
which stores something and has one of the values from my enum
.
public class Thing
{
public final Categories category;
public int var;
public Thing (Categories category) {
this.category = category;
}
}
All good. Now I know I will have exactly four things. I can change which things, I can set them to null, but I will always have one of each. I will always have exactly one A
,B
, C
and one D
. No more no less. So I store them in my Container
. Like this.
public class Container
{
private final Map<Categories, Thing> things = new HashMap<>();
public Container () {
for (int i = 0; i < Categories.values().length; i++) {
things.put(Categories.values()[i], null);
}
}
public Thing getThing (Categories c) {
return things.get(c);
}
public Thing setThing (Categories c, Thing t) {
Thing returnThing = null;
if (things.containsKey(c) && t.category == c) {
if (things.get (c) != null) {
returnThing = things.get (c);
}
things.put(c, t);
}
return returnThing;
}
public Thing removeThing (Categories c) {
Thing returnThing = null;
if (things.containsKey(c) && things.get(c) != null) {
returnThing = things.get(c);
things.put (c, null);
}
return returnThing;
}
}
While this code works, it feels a bit clunky. As I know I will never add another key
, nor remove one. Is there any pattern I lack the knowledge of that solves this issue? Or, doubt it, is this the way to accomplish a task such as this?
I would prefer to stay away from external dependencies such as Guava
.