Reputation: 35
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);
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);
}
}
}
Upvotes: 3
Views: 20619
Reputation: 959
courseName.add is not possible.. courseName is a String, which being a immutable object doesn't allow any add method...
check out: 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!
Upvotes: 0
Reputation: 11733
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.
Upvotes: 2