I'm using a Hashmap as my in-memory cache. So basically, this is what I have:
private static final Map<String, Object> lookup = new HashMap<String, Object>();
public static Object get(CacheHelper key) {
return lookup.get(key.getId());
}
public static void store(CacheHelper key, Object value) {
lookup.put(key.getId(), value);
}
That's fine. But for every Object I "get" from the Map, I have to cast, which is very ugly. I want to put ArrayList and many other different things into it.
Does anybody know an other solution to be typesafe ?
(For sure, I can create for every type a getter and setter, but is that the only solution ?
So, is there a better way to create an in-memory cache or does somebody have an idea how to wrap the hashmap to be more safe ?
One solution to this problem is to make your CacheHelper type generic, with
CacheHelper<T>
. Then create a wrapper for your map:The Java compiler actually uses this approach internally; see e.g. here. You don't have to pass around explicit
Class
objects, but you do have to know what type is actually associated with each key, which is as it should be in well-behaved applications.