For each loop on Java HashMap

后端 未结 4 1868
抹茶落季
抹茶落季 2021-02-05 08:21

A basic chat program I wrote has several key words that generate special actions, images, messages, etc. I store all of the key words and special functions in a HashMap. Key wor

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 09:21

    A better pattern here might be:

    Value val = hashMap.get(user.getInput());
    if (val != null) {
        doVal();
    }
    else {
        // handle normal, non-keyword/specfial function
    }
    

    which takes advantage of the fact that HashMap returns null if the key isn't contained in the Map.

提交回复
热议问题