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> maps value<integer>
  • key<string> maps value<string>
  • key<double> maps value<double>

however, invalid:

  • key<integer> mapping value<string>
  • key<double> mapping value<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

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -