我有一张地图,handicapMap,一个整数键,以及一组字符串。地图已经填充了测试数据,我现在希望将各个值添加到字符串集中。我尝试了它,但无法编译它
public class HandicapRecords
{
private Map<Integer, Set<String>> handicapMap;
public HandicapRecords()
{
handicapMap = new HashMap<>();
}
public void handicapMap()
{
Set<String> players = new HashSet<>();
players.add("Michael");
players.add("Roger");
players.add("Toby");
handicapMap.put(10, players);
players = new HashSet<>();
players.add("Bethany");
players.add("Martin");
handicapMap.put(16, players);
players = new HashSet<>();
players.add("Megan");
players.add("Declan");
handicapMap.put(4, players);
}
public void addValue(int aKey, String aValue)
{
handicapMap.put(aKey, players.add(aValue)); \\what I had already tried
}
答案 0 :(得分:0)
Set#add
返回boolean
,主要取决于该值是否已添加 - 请参阅API。
您想要用来向Map
值添加新值的惯用语(即Set<String>
),其关键是:
handicapMap.get(aKey).add(aValue);
您可能还应首先检查空Map
值:
Set<String> theValue = handicapMap.get(aKey);
if (theValue != null) {
theValue.add(aValue);
}
答案 1 :(得分:0)
试试这个:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class HandicapRecords {
private Map<Integer, Set<String>> handicapMap;
public HandicapRecords() {
handicapMap = new HashMap<>();
}
Set<String> players = new HashSet<>();
public void handicapMap() {
players.add("Michael");
players.add("Roger");
players.add("Toby");
handicapMap.put(10, players);
players = new HashSet<>();
players.add("Bethany");
players.add("Martin");
handicapMap.put(16, players);
players = new HashSet<>();
players.add("Megan");
players.add("Declan");
handicapMap.put(4, players);
}
public void addValue(int aKey, String aValue) {
players.add(aValue);
handicapMap.put(aKey, players);
}
}
答案 2 :(得分:0)
将Set<String> players
声明为实例变量或在amethod内部声明,并且不要忘记检查地图是否为null
,因为这会导致NPE
。
public void addValue(int aKey, String aValue)
{
Set<String> players = new HashSet<>();
if(handicapMap!=null){
handicapMap.put(aKey, players.add(aValue));
}
}
答案 3 :(得分:0)
试试这个
public void addValue(int aKey, String aValue)
{
if (handicapMap.containsKey(aKey)) {
handicapMap.get(aKey).add(aValue); // May want to add a check if the key has no values
}
}
答案 4 :(得分:0)
首先,您需要检查是否已存在该密钥的映射。如果是这种情况,您只需要将值添加到现有集合中。否则,您需要先创建集合并将其添加到地图中,然后将新值添加到该集合中。
public void addValue(int aKey, String aValue)
{
Set<String> players = handicapMap.get(aKey);
if (players == null) {
players = new HashSet<>();
handicapMap.put(aKey, players);
}
players.add(aValue);
}