Java generics enforce same type for keys and values of map -
what looking for:
i'm looking construct enforces type on both keys , values of map: kind of map<key<x>, value<x>>
. however, additionally enforce types match within each key/value entry, between entries, no type must should enforced.
for example, within same map, these key/value pairs should considered valid:
key<integer>
mapsvalue<integer>
key<string>
mapsvalue<string>
key<double>
mapsvalue<double>
however, invalid:
key<integer>
mappingvalue<string>
key<double>
mappingvalue<boolean>
how can accomplish using java generics?
what i'm not looking for:
i understand can implement
set<pair>
, pair accepts key/value of same type. however, looking key no longer constant time operation.i understand
map<key<?>, value<?>>
, assert key , value same type @ runtime. however, wondering if possible strictly using generics.
you can this, have roll own wrapper on top of map
:
class mytypesafemap { private map<key<?>, value<?>> map; public <t> void put(key<t> key, value<t> value) { map.put(key, value); } public <t> value<t> get(key<t> key) { return (value) map.get(key); // know it's safe, compiler can't prove } }
compare e.g. guava's classtoinstancemap
.
Comments
Post a Comment