HashSet写班级删除
时间: 2023-12-26 09:06:46 浏览: 65
好的,以下是一个示例代码,展示如何使用HashSet来实现班级学生的删除:
```java
import java.util.*;
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student student = (Student) obj;
return id == student.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
public class Classroom {
private String name;
private Set<Student> students;
public Classroom(String name) {
this.name = name;
this.students = new HashSet<>();
}
public boolean addStudent(Student student) {
return students.add(student);
}
public boolean removeStudent(Student student) {
return students.remove(student);
}
public void displayStudents() {
System.out.println("Students in " + name + ":");
for (Student student : students) {
System.out.println("ID: " + student.getId() + ", Name: " + student.getName());
}
}
public static void main(String[] args) {
Classroom classroom = new Classroom("Class A");
// 添加几个学生
Student s1 = new Student(1, "Alice");
Student s2 = new Student(2, "Bob");
Student s3 = new Student(3, "Charlie");
classroom.addStudent(s1);
classroom.addStudent(s2);
classroom.addStudent(s3);
classroom.displayStudents();
// 删除一个学生
boolean deleted = classroom.removeStudent(s2);
if (deleted) {
System.out.println("Student with ID " + s2.getId() + " has been removed.");
} else {
System.out.println("Student with ID " + s2.getId() + " not found.");
}
classroom.displayStudents();
}
}
```
在这个示例代码中,我们首先定义了一个`Student`类,包含学生的ID和姓名属性。然后定义了`Classroom`类,包含班级名称和学生集合。在`Classroom`类中,我们使用了HashSet来存储学生。`addStudent()`方法用于添加一个学生,`removeStudent()`方法用于删除一个学生,`displayStudents()`方法用于打印班级中所有学生的信息。
在`main()`方法中,我们创建了一个`Classroom`对象,添加了三个学生,并打印了所有学生的信息。然后我们删除了一个学生,再次打印了所有学生的信息。注意,我们在调用`removeStudent()`方法时,将要删除的学生对象作为参数传递给了它。如果成功删除了学生,`removeStudent()`方法返回`true`,否则返回`false`。
阅读全文