How to name a HashMap in Java?
I don't believe there is a hard-written rule anywhere that tells you how to name your map, so as long as you come up with a rule that makes sense to you (and your teammates), then it should be fine.
Personally, I like to call my maps keyToValue
or valueByKey
.
I like this question because Java does not allow map access via an operator like []
. In other languages we could say things like
numberOfCountiesIn["HI"]
or
countyCountOf["CA"]
or
numCountiesIn->{"MA"}
or (in Scala, this is cool)
numCountiesIn("WA")
and on and on. None of these work in Java, because of that silly get
word!
countyCounts.get("NY")
Indeed!
EDIT: I actually think countyCounts
is the best answer (IMHO); I was just making the point that the need for get
limits one's choices.
Firstly avoid putting implementation details in the name of a variable, e.g. StateToCountyMap
. Today you are using a Map
interface but tomorrow you can decide to store your data in another type and the name of your variable has to be refactored otherwise it will become invalid and misleading.
Your data represents association of a state to its number of counties, so my advice is to name the variable as stateToNumberOfCounties
. The key point in this name is to
which designates that this variable stores an association, the part before that is the key
and the part after is the value
or values
that are associated to the corresponding key
. Also it would be indistinct to name the variable as stateToCountyNumber
because one could not tell if it stores relation between a state and its number of counties or it stores a single number that represents the number of state to county associations, thus you would have to go back and forth in your code to check if it is of type Map
or of type int
.