gpt4 book ai didi

java - 如何向哈希集添加值?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:29:47 24 4
gpt4 key购买 nike

我正在做一道练习题,要求我将一个值添加到 HashMap 中。但我不明白为什么我一直在 courseName.add(student);

行收到错误消息

这是我的代码:

public class StudentDatabase {

// add instance variables
private Map<String, HashSet<Integer>> dataContent = new LinkedHashMap<String, HashSet<Integer>>();

// Prints a report on the standard output, listing all the courses and all the
// students in each. If the map is completely empty (no courses), prints a message
// saying that instead of printing nothing.
public void report() {
if (dataContent.isEmpty()) {
System.out.println("Student database is empty.");
} else {
for (String key : dataContent.keySet()) {
System.out.println(key + ":" + "\n" + dataContent.get(key));
}
}
}

// Adds a student to a course. If the student is already in the course, no change
// If the course doesn't already exist, adds it to the database.
public void add(String courseName, Integer student) {
if (dataContent.containsKey(courseName)) {
courseName.add(student);
} else {
Set<Integer> ids = new HashSet<Integer>();
ids.add(student);
dataContent.put(courseName, ids);
}
}
}

最佳答案

好的,这个结构:

if (dataContent.containsKey(courseName)) {
courseName.add(student);
}

完全古怪。你想要的是:

if (dataContent.containsKey(courseName)){
Set<Integer> studentsInCourse = dataContent.get(courseName);
studentsInCourse.add(student);
}

应该修复它。

关于java - 如何向哈希集添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com