作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在做一道练习题,要求我将一个值添加到 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/
我是一名优秀的程序员,十分优秀!