我正在使用 HashMap 构建同义词库来存储同义词。
我正在尝试根据正则表达式搜索单词:该方法必须将字符串作为参数并返回结果数组。这是我的第一次尝试:
public ArrayList<String> searchDefinition(String regex) {
ArrayList<String> results = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
Set<String> keys = thesaurus.keySet();
Iterator<String> ite = keys.iterator();
while (ite.hasNext()) {
String candidate = ite.next();
Matcher m = p.matcher(candidate);
System.out.println("Attempting to match: " + candidate + " to " + regex);
if (m.matches()) {
System.out.println("it matches");
results.add(candidate);
}
}
if (results.isEmpty()) {
return null;
}
else {
return results;
}
}
现在,这不像我预期的那样工作(或者我可能错误地使用了正则表达式)。如果我在哈希图中有以下键:
cat, car, chopper
然后通过调用searchDefinition("c")
或searchDefinition("c*")
我得到null
。
- 我如何使这项工作按预期进行?
- 是否有比 HashMap 更好的数据结构来保持
graph
同义词库所需的相似?(只是好奇,至于这个作业,我们被要求使用 Java Collection Map)。 - 我在上面的代码中还有什么不恰当的地方吗?
谢谢,丹
编辑:我已经更正了这个例子。即使我使用正确的案例,它也不起作用。