In my answer from yesterday I called the following piece of code “a hack”:
final class MyMap extends HashMap<SomeSuperLongIdentifier, OtherSuperLongIdentifier> {}
// declared MyMap as an alias for readability purposes only
MyMap a = new MyMap();
a.put("key", "val");
Giving it another thought, this does not seem like a bad idea at all, but I might be missing something. Are there any potholes I missed out on? Is this an acceptable (possibly creative) way for declaring aliases in Java?
The drawback would be that you won’t be able to directly use any methods that return a correctly typed
Map, because they will never return aMyMap. Even if they could return aMap<SomeSuperLongIdentifier, OtherSuperLongIdentifier>.For example you wouldn’t be able to use the
filter()methods inMaps(provided by Google Collections). They would accept aMyMapinstance as input, but they would return only aMap<SomeSuperLongIdentifier, OtherSuperLongIdentifier>.This problem can be somewhat reduced, by writing your
MyMapto delegate to anotherMapimplementation. Then you could pass the return value of such a method into the constructor and still have aMyMap(without copying, even). The default constructor could just set the delegate to a newHashMapinstance, so the default usage would stay the same.