Part (a)
// adds syn to the set of synonyms associated with word
// in this Thesaurus;
// if word is not a key in this Thesaurus, adds an
// entry with word as key and a set containing syn
// as the associated value
public void addSynonym(String word, String syn)
{
Set synonyms = (Set)wordMap.get(word);
if (synonyms == null)
{
synonyms = new TreeSet(); 1
wordMap.put(word, synonyms);
}
synonyms.add(syn); 2
}
Notes:
- Or
HashSet .
- It is okay to first put
synonyms into the map,
then add an element to it, because synonyms is a value, not a key.
Part (b)
// removes the word syn from each synonym set in this Thesaurus;
// returns a set of the words (keys) whose associated
// synonym sets originally contained the word syn;
// if syn was not contained in any synonym set, returns an empty set
public Set removeSynonym(String syn)
{
Set affectedWords = new TreeSet();
Iterator iter = wordMap.keySet().iterator();
while (iter.hasNext())
{
String word = (String)iter.next();
Set synonyms = (Set)wordMap.get(word);
if (synonyms.contains(syn))
{
synonyms.remove(syn);
affectedWords.add(word);
}
}
return affectedWords;
}
|