What I am looking for:
I'm looking to construct something that enforces type on both the keys and values of a map: kind of like Map<Key<X>, Value<X>>. However, I would additionally like to enforce that types match within each key/value entry, but between entries, no type must should be enforced.
For example, within the same map, these key/value pairs should be considered valid:
Key<Integer>maps toValue<Integer>Key<String>maps toValue<String>Key<Double>maps toValue<Double>
However, something like this would be invalid:
Key<Integer>mapping toValue<String>Key<Double>mapping toValue<Boolean>
How can I accomplish this using Java generics?
What I'm not looking for:
I understand that I can implement something like
Set<Pair>, where pair accepts Key/Value of the same type. However, looking this up by key would no longer be a constant time operation.I understand that I could do something like
Map<Key<?>, Value<?>>and just assert that the Key and Value are the same type at runtime. However, I was wondering if this is possible strictly using generics.
Mapanywhere that just enforces "The keys must be of the same type as the values (or have the same generic type within them, in the case ofKey<X>/Value<X>), but each key/value pair can be of a different type."