2

好的,这就是我要做的:

将传递的内容拆分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
}

一切正常,但现在我的任务说,如果任何行的键重复(多次出现),我需要抛出异常。

据我了解,键只能是唯一的,那么我在这里缺少什么?

4

3 回答 3

8

一旦添加到 中,键是唯一的,但是您可以通过使用or方法HashMap查询哈希映射来知道要添加的下一个是否已经存在。containsKey(..)get(..)

于 2013-01-28T01:25:59.643 回答
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]
于 2013-01-28T06:50:42.477 回答
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
    }

}
于 2013-01-28T01:34:10.453 回答