班级和学生是一对多的关系 用java代码实现增删改查
时间: 2024-03-02 16:53:22 浏览: 28
下面是一个班级和学生的一对多关系的Java代码示例:
```java
import java.util.ArrayList;
import java.util.List;
public class Class {
private int id; // 班级ID
private String name; // 班级名称
private List<Student> students; // 学生列表
public Class(int id, String name) {
this.id = id;
this.name = name;
this.students = new ArrayList<>();
}
// 添加学生
public void addStudent(Student student) {
students.add(student);
}
// 删除学生
public void removeStudent(Student student) {
students.remove(student);
}
// 修改学生
public void updateStudent(Student student) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() == student.getId()) {
students.set(i, student);
}
}
}
// 获取学生列表
public List<Student> getStudents() {
return students;
}
// 根据ID获取学生
public Student getStudentById(int id) {
for (Student student : students) {
if (student.getId() == id) {
return student;
}
}
return null;
}
// 根据姓名获取学生列表
public List<Student> getStudentByName(String name) {
List<Student> result = new ArrayList<>();
for (Student student : students) {
if (student.getName().equals(name)) {
result.add(student);
}
}
return result;
}
}
public class Student {
private int id; // 学生ID
private String name; // 学生姓名
private int age; // 学生年龄
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
在这个示例中,Class类表示班级,包含一个班级ID、班级名称和学生列表;Student类表示学生,包含一个学生ID、学生姓名和学生年龄。
Class类中的addStudent方法用于添加学生,removeStudent方法用于删除学生,updateStudent方法用于修改学生,getStudents方法用于获取学生列表,getStudentById方法用于根据ID获取学生,getStudentByName方法用于根据姓名获取学生列表。
需要注意的是,在班级和学生的一对多关系中,班级是一方,学生是多方。因此,在Class类中,使用一个List来保存学生列表。在Student类中,没有保存班级信息,因为一个学生只属于一个班级。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)