Is it possible to declare a Map that maps from keys of a specific subclass to values of a specific subclass but ensuring that both classes share the same Type parameter?
For the background:
both ClassA and ClassB implement behaviour for a common resource
public abstract class ClassA<T> {
public abstract T getResource() ;
}
public abstract class classB<T> {
public abstract void consoumeResource(T resource);
}
i want to map from implementations of ClassA and ClassB and ensure only “compatible” pairs can be put together in one entry.
Another way would be to provide your own
Mapimplementation. There’s not much code needed if you extend an existing implementation, and use your new type:Now, a
CompatibleHashMap<String>only lets you putClassA<String>as keys andClassB<String>as values.EDIT:
As you mentioned in your comment, this way you are tying yourself to a
Mapimplementation. You can overcome this by doing something like the following:You can then instantiate it like
This way, you are not tied to a specific
Mapimplementation, and the compiler will throw an error if the generic types of themap,ClassAandClassBare not the same.