好的,这就是我要做的事情:
将传递的List
拆分为单独的行,然后使用分隔符拆分这些行,然后将这些部分添加到Map
。
我的代码:
public GrammarSolver(List<String> rules) {
if(rules == null || rules.size() == 0) {
throw new IllegalArgumentException();
}
Map<String, String> rulesMap = new HashMap<String, String>();
Iterator<String> i = rules.iterator();
while(i.hasNext()) {
String rule = i.next(); // store a line from 'rules' List
String[] parts = rule.split("::="); // split the line into non-terminal and terminal
rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
}
// TODO: exception when duplicate key in map
}
一切正常,但现在我的任务说如果任何行的键重复(多次出现),我需要抛出异常。
根据我的理解,钥匙只能是唯一的,所以我在这里缺少什么?
答案 0 :(得分:7)
一旦添加到HashMap
,密钥就是唯一的,但您可以通过使用containsKey(..)
或get(..)
方法查询哈希地图来了解您要添加的下一个密钥是否已存在
答案 1 :(得分:1)
只需将行添加到行
即可rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
像
// Put the two parts into the map
if((String existing = rulesMap.put(parts[0], parts[1])) != null)
throw new IllegalStateException(
"duplicated key " + parts[0]
+ " with value " + existing + " overwritten by " + parts[1]
答案 2 :(得分:0)
您可以写如下:
while(i.hasNext()) {
String rule = i.next(); // store a line from 'rules' List
String[] parts = rule.split("::="); // split the line into non-terminal and terminal
if(rulesMap.containsKey(parts[0]){
throw New Excpetion(...);
}else{
rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
}
}