【发布时间】:2018-03-14 03:40:10
【问题描述】:
嘿,我正在实现这个功能。
private static HashMap<String, Set<String>> enrollments = new HashMap<String, Set<String>>();
private static Set<String> studentset;
/**
* Enrolls a student into a unit.
*
* @param unit
* @param student
*/
public static void enroll(String unit, String student) {
if(!enrollments.containsKey(unit)) {
studentset = new HashSet<String>();
}
studentset.add(student);
enrollments.put(unit, studentset);
}
/**
* Gets a list of all students of a particular discipline. E.g. If discipline is
* "ABC" then return a collection of all students enrolled in units that start
* with "ABC", so ABC301, ABC299, ABC741 etc. This method is non-trivial so it
* would help to first implement the helper method matchesDiscipline (below).
*
* @param discipline
* @return
*/
public static Set<String> getStudents(String discipline) {
Set<String> myList = new HashSet<String>();
for (Entry<String, Set<String>> e : enrollments.entrySet()) {
if (e.getKey().startsWith(discipline)) {
myList.addAll(e.getValue());
}
}
return myList;
}
public static void main(String[] args) {
EnrollmentManager.enroll("CAB302", "James");
EnrollmentManager.enroll("CAB403", "Ben");
EnrollmentManager.enroll("CAB302", "James");
EnrollmentManager.enroll("CAB403", "Morgan");
EnrollmentManager.enroll("CAB404", "Sam");
System.out.println(EnrollmentManager.getStudents("CAB3"));
}
我遇到的问题是“myList”正在输出 [Morgan, James, Ben]。正确答案是[詹姆斯]。我哪里错了?抱歉,如果它是 Collections 新手的简单解决方案。
【问题讨论】:
-
你能粘贴你的
enroll函数吗? -
另外,预期的输出不应该是 James 吗?因为
e.getKey().startsWith(discipline)将匹配您的输入“CAB3”,根据您的数据,似乎只有 James 匹配它。 -
我已经更新了帖子
-
IMO 如果地图是
<Student, List<Units>>会更有意义 -
@Sam 你的问题解决了吗?
标签: java list collections set