java 如何向散列集添加值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15892736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add a value to a hash set?
提问by user2259968
I'm working on a practice problem that requires me to add a value into a hashmap. But I can't figure out why I keep getting an error message on the line courseName.add(student);
我正在解决一个练习问题,该问题需要我将一个值添加到哈希图中。但我想不通为什么我总是收到一条错误消息courseName.add(student);
Here is my code:
这是我的代码:
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);
}
}
}
采纳答案by Rob
Ok, this construct:
好的,这个构造:
if (dataContent.containsKey(courseName)) {
courseName.add(student);
}
is completely whacky. What you want is:
完全古怪。你想要的是:
if (dataContent.containsKey(courseName)){
Set<Integer> studentsInCourse = dataContent.get(courseName);
studentsInCourse.add(student);
}
Should fix it.
应该修复它。
回答by prashantsunkari
courseName.add is not possible.. courseName is a String, which being a immutable object doesn't allow any add method...
courseName.add 是不可能的.. courseName 是一个字符串,它是一个不可变的对象,不允许任何添加方法......
check out: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
查看:http: //docs.oracle.com/javase/7/docs/api/java/lang/String.html
I think this is what you are looking for:
我认为这就是你要找的:
public void add(String courseName, Integer student) {
if (dataContent.containsKey(courseName)) {
HashSet<Integer> newhashSet=dataContent.get(courseName);
if(newhashSet!=null)
{
newhashSet.add(student);
}
dataContent.put(courseName, newhashSet);
//courseName.add(student);
}
else {
Set<Integer> ids = new HashSet<Integer>();
ids.add(student);
dataContent.put(courseName, (HashSet<Integer>) ids);
}
// System.out.println("Data:"+dataContent.toString());
} // end add
}
Hope this helps!
希望这可以帮助!