arraylist - Use Java HashMap multiple Type -
i'm using hashmap in-memory cache. basically, 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. every object "get" map, have cast, ugly. want put arraylist , many other different things it.
does know other solution typesafe ?
(for sure, can create every type getter , setter, solution ?
so, there better way create in-memory cache or have idea how wrap hashmap more safe ?
one solution problem make cachehelper type generic, cachehelper<t>
. create wrapper map:
class mycache { private final map<cachehelper<?>, object> backingmap = new hashmap<>(); public <t> void put(cachehelper<t> key, t value) { backingmap.put(key, value); } @suppresswarnings("unchecked") // long entries put in via put, cast safe public <t> t get(cachehelper<t> key) { return (t) backingmap.get(key); } }
the java compiler uses approach internally; see e.g. here. don't have pass around explicit class
objects, have know type actually associated each key, should in well-behaved applications.
Comments
Post a Comment