这就是我到目前为止所拥有的以及我想要做的,我不知道如何访问拆分的两个部分,此代码确实是错误的,但我不知道如何做我想做的事情(是的,这是为了学校)
public class Relatives
{
private Map<String,Set<String>> map;
/**
* Constructs a relatives object with an empty map
*/
public Relatives()
{
map = new TreeMap<String,Set<String>>();
}
/**
* adds a relationship to the map by either adding a relative to the
* set of an existing key, or creating a new key within the map
* @param line a string containing the key person and their relative
*/
public void setPersonRelative(String line)
{
String[] personRelative = line.split(" ");
if(map.containsKey(personRelative[0]))
{
map.put(personRelative[0],map.get(personRelative[1])+personRelative[1]);
}
else
{
map.put(personRelative[0],personRelative[1]);
}
}
我正在尝试访问此人并将其添加到当前的亲戚中,如果不存在,则创建一个与该亲戚相关的新人
我如何格式化它以便它像这样返回
Dot is related to Chuck Fred Jason Tom
Elton is related to Linh
我有这个,但出现错误
public String getRelatives(String person)
{
return map.keySet();
}
最佳答案
您不能使用 +=
运算符将项目添加到 Set 中;您必须使用 add
方法。
此外,您必须在第一次使用它时创建该集合。
固定代码可能如下所示:
String[] personRelative = line.split(" ");
String person = personRelative[0];
String relative = personRelative[1];
if(map.containsKey(person))
{
map.get(person).add(relative);
}
else
{
Set<String> relatives = new HashSet<String>();
relatives.add(relative);
map.put(person,relatives);
}
关于java - 函数映射错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19040387/