Ok so here’s what I have to do:
Split the passed List into individual lines, and then split those lines using a delimiter and then add those parts to a Map.
My code:
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
}
Everything works fine, but now my assignment says that I need to throw an exception if the key of any line is duplicated (occurring more than once).
From what I understand, keys can only be unique, so what am I missing here?
Keys are unique once added to the
HashMap, but you can know if the next one you are going to add is already present by querying the hash map withcontainsKey(..)orget(..)method.