如何向哈希集添加值?

时间:2013-04-09 03:22:38

标签: 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);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

好的,这个结构:

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

完全是个傻瓜。你想要的是:

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

应该修理它。

答案 1 :(得分:0)

courseName.add是不可能的.. courseName是一个String,它是一个不可变对象,不允许任何添加方法......

结帐: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
 }

希望这有帮助!