3

我正在处理一个需要我将值添加到哈希图中的练习问题。但我不明白为什么我一直在线收到错误消息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);
        }
    }
}
4

2 回答 2

2

好的,这个构造:

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

完全是古怪的。你想要的是:

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

应该修复它。

于 2013-04-09T03:27:55.490 回答
0

courseName.add 是不可能的.. courseName 是一个字符串,它是一个不可变对象,不允许任何 add 方法...

签出:http ://docs.oracle.com/javase/7/docs/api/java/lang/String.html

我认为这就是你要找的:

    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
 }

希望这可以帮助!

于 2013-04-09T03:27:49.660 回答