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

标签 java hashset

我正在做一道练习题,要求我将一个值添加到 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/

相关文章:

java - 迭代一个集合并创建一个包含 HTML 的字符串

java - 将数组中的单词放入 HashMap 和 HashSet

java - 从交集java获取第一个元素

java - System.out.println() 的替代语句

java - 从 Firebase 读取数据时出现 NullPointerException

java - JPA 给自己惹麻烦

c# - .Net Collection 用于雾化T?

c# - 我有一个包含超过一百万个对象的列表,试图找到最快的搜索方式

java - 更新java数据库中的记录值

java - 在java中的Jtable中获取多个原始数据