我想让一个学生退学。以下方法没有删除该值?想法请:
public static void withdrawStudent(String student) { enrollments.values().remove(student); } public static void main(String[] args) { enroll("101", "Pat"); withdrawStudent("Pat"); }
//这是课程的一部分。
private static HashMap<String, Set<String>> enrollments = new HashMap<String, Set<String>>(); public static void enroll(String unit, String student) { Set<String> studentsSet = enrollments.get(unit); if(studentsSet == null) { studentsSet = new HashSet<>(); } studentsSet.add(student); enrollments.put(unit, studentsSet); }
您的问题是,您试图删除字符串,而 enrollments.values() 返回一组字符串。一个可能的解决方法是这样,但请记住,这将从每次注册中删除该学生。
enrollments.values()
public static void withdrawStudent(String student) { for (Set<String> studentSet : enrollments.values()) { studentSet.remove(student); } }