How to name a HashMap in Java?

2019-03-14 05:59发布

This might be a silly question, but I have never found a satisfying way to name a variable of type HashMap<K,V> in Java. For example - lets say I have a HashMap where every bucket is a <K,V> pair where K is a String say representing "State" and V is an Integer representing the number of counties the state has.

Should the HashMap be named as "mapStateCounty", "stateToCountyMap", etc. ? Which one seems logically more appealing and intuitive to understand without sounding confusing and verbose?

9条回答
欢心
2楼-- · 2019-03-14 06:12

Whatever explains it best - In this case stateToCountyMap is ok or else countiesInStateMap can be used.

查看更多
家丑人穷心不美
3楼-- · 2019-03-14 06:18

Storing states and counties in that variable it would be confusing to name it map - call it stateCountyHash or numCountiesByState

查看更多
唯我独甜
4楼-- · 2019-03-14 06:27

I would call it numCounties or countyCounts.

查看更多
该账号已被封号
5楼-- · 2019-03-14 06:28

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.

查看更多
贪生不怕死
6楼-- · 2019-03-14 06:34

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.

查看更多
萌系小妹纸
7楼-- · 2019-03-14 06:37

I found a great case for countiesByState here:

valuesByKeys, as in teamsByCaptains. If you're going to include both key and value, this seems to read best. At a high level, you can read it as just "teams", so anything that's performed on it is being performed on teams. The "byCaptains" prefix reads as it should do: a less significant qualifier that follows the teams around to help someone understand the structure if they need to.

This also allows you to access a value in a JSP with the nice notation countiesByState[myState].

查看更多
登录 后发表回答