I recently ran across a set of code which instantiated local maps as following:
HashMap<String, Object> theMap = new HashMap<String, Object>();
Typically, when I’ve seen HashMaps used (and used them myself), the local variables are simply Map (the interface), rather than being tied to the specific implementation. Obviously this is required if the Map could potentially be instantiated as various Map types (e.g. accepting a parameter). However, in the case of something like the above where it’s defined and instantiated at the same point, is there an underlying reason to only use the interface type, or is it simply style/convention?
(I originally misunderstood the question based on the title, but I’ve included both type and variable conventions as both are interesting.)
What’s important is that it’s a map: something you look things up in. The rest is an implementation detail.
I would suggest giving it a semantic name, e.g.
… that way when you read the code, you’ll know what the keys and values are meant to be.
As for the type of the variable – again, I’d typically use the interface rather than the implementation partly because it indicates I’m not using any members which are specific to the type. I don’t want to emphasize the implementation in the code, usually… it means when I do care about the implementation, I can make that more obvious.